-->

Trouble creating custom hash function unordered_ma

2019-09-18 01:33发布

问题:

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.