2015-02-05 54 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; 
} 

你的問題很可能是在其他地方。