Trouble creating custom hash function unordered_map?

≡放荡痞女 提交于 2019-12-25 12:43:52

问题


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());
    }
};

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!


回答1:


This code 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;
}

Your problem is likely elsewhere.



来源:https://stackoverflow.com/questions/28355522/trouble-creating-custom-hash-function-unordered-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!