Reputation: 46393
When doing
unordered_map<pair<unsigned int, unsigned int>, unsigned int> m;
we get
Error C2338: The C++ Standard doesn't provide a hash for this type.
Is there a built-in way to define a hash for a std::pair
of int
or do we need to define it manually? (in this case, the hash could be just (the bytes of first item)(the bytes of second item of the pair) glued together).
Note: I'm using VC++ 2013.
Note2: the answer to pair<int,int> pair as key of unordered_map issue doesn't clearly address the question of how to actually create the hash with two int
s, as detailed here.
Upvotes: 4
Views: 6419
Reputation: 6131
If you don't want to use boost, rolling your own shouldn't be too hard. static_assert added to ensure the assumption that 2 ints fit into 1 size_t is maintained.
using IntPair = std::pair<int, int>;
struct IntPairHash {
static_assert(sizeof(int) * 2 == sizeof(size_t));
size_t operator()(IntPair p) const noexcept {
return size_t(p.first) << 32 | p.second;
}
};
std::unordered_map<IntPair, int, IntPairHash> myMap;
Upvotes: 5