麻烦创建自定义哈希函数unordered_map? [英] Trouble creating custom hash function unordered_map?

查看:734
本文介绍了麻烦创建自定义哈希函数unordered_map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为一个无序的地图创建一个自定义哈希函数。我发现这个问题:<一href=\"http://stackoverflow.com/questions/10405030/c-unordered-map-fail-when-used-with-a-vector-as-key\">C++用向量作为重点使用,并发现,如果你使用一个向量作为一个无序的地图一键,你需要创建自己的散列函数时,unordered_map失败。我尝试复制写成这样哈希函数:

I wanted to create a custom hash function for an unordered map. I found this question: C++ unordered_map fail when used with a vector as key and found that if you use a vector as a key in an unordered map, you need to create your own hash function. I experimented copying the hash function written as so:

template <typename Container> 
struct container_hash {
    std::size_t operator()(Container const& c) const {
        return boost::hash_range(c.begin(), c.end());
    }
};

但是,当我尝试创建我的钥匙了unordered_map像这样的整数的向量:

But when I try to create an unordered_map with my keys as a vector of ints like so:,

unordered_map<vector<int>, int, container_hash<vector<int>>> hash;

我得到的一个问题说:

I get an issue saying that:

error: declaration of ‘struct std::hash<std::vector<int> >’

我曾尝试其他方法试图通过之类的东西。

I have tried other ways to include the container_hash function into the implementation of my unordered_map by trying things like

unordered_map<vector<int>, int, container_hash> hash;

不过,我又得到另一个错误说:

But again I get another error saying:

type/value mismatch at argument 3 in template parameter list for ‘template<class _Key, class _Tp, class _Hash, class _Pred, class _Alloc> class std::unordered_map’

我真的不知道如何解决这个问题,如果有人可以帮助我,这将是伟大的!谢谢!

I'm really not sure how to get around this, if anyone could help me that would be great! Thanks!

推荐答案

这code 编译就好

#include <vector>
#include <boost/unordered_map.hpp>

template <typename Container>
struct container_hash {
    std::size_t operator()(Container const& c) const {
    return boost::hash_range(c.begin(), c.end());
    }
};

int main()
{
    boost::unordered_map
        <std::vector <int>, int,
         container_hash <std::vector  <int> > > foo;
    return 0;
}

您的问题可能是在其他地方。

Your problem is likely elsewhere.

这篇关于麻烦创建自定义哈希函数unordered_map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆