busebd12 busebd12 - 1 year ago 206
C++ Question

Error: static_assert failed "This hash only works for enumeration types" for unordered_multimap

I'm trying to insert into an

unordered_multimap<pair<int, int>, int>

like so:

unordered_multimap<pair<int, int>, int> tree;

auto firstPair=make_pair(firstNumber, secondNumber);

tree.insert(make_pair(firstPair, 0));

However, the compiler proceeds to greet me with the following error upon compilation:

error: static_assert failed "This hash only works for enumeration types"

Now, after some Google-fu and reading other questions (this and this) here regarding this error, only with unordered_map instead, I've come to the conclusion that I need to provide my own hash function. However, this is confusing to me since the other questions I've read seem to involve keys that were custom (user-defined) classes and I don't consider a the type of key I'm using to be "custom." If anyone could provide insight on this, I would greatly appreciate it!

Answer Source

The STL doesn't define a hash function for std::pair. So you need to do the same thing as you would do if std::pair<int, int> was a type you created. You should declare your own implementation of std::hash.

However, that is not what I recommend. Instead, you'll probably find it easier to use a map of maps: unordered_map<int, unordered_multimap<int, int>>.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download