2015-02-05 75 views
0

我想为无序映射创建自定义哈希函数。我发现这个问题:C++ unordered_map fail when used with a vector as key,发现如果你在无序映射中使用向量作为键,你需要创建你自己的散列函数。我尝试复制写成这样的哈希函数:麻烦创建自定义哈希函数unordered_map?

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

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

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

INTS的载体,我得到的一个问题说, :

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

我已经尝试新事物尝试其他方式包括container_hash功能到我unordered_map执行类似

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

但我又得到另一个错误说:

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’ 

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

+0

什么编译器?你的第一个定义是gcc和clang [接受](http://coliru.stacked-crooked.com/a/e4988e4aad76243f)。 – Praetorian 2015-02-05 22:55:29

+0

我正在尝试编写一个使用MPI的程序,所以我使用的是mpicxx编译器@Praetorian – user1871869 2015-02-05 22:58:53

+0

看看它是否会编译我链接的代码,如果不是,那可能是编译器的问题。 – Praetorian 2015-02-05 23:00:58

回答

1

此代码compiles just fine

#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; 
} 

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