I need to define an unordered_map like this unordered_map<pair<int, int>, *Foo>
, what is the syntax for defining and passing a hash
and equal
functions to this map?
I've tried passing to it this object:
class pairHash{
public:
long operator()(const pair<int, int> &k) const{
return k.first * 100 + k.second;
}
};
and no luck:
unordered_map<pair<int, int>, int> map = unordered_map<pair<int, int>, int>(1,
*(new pairHash()));
I have no Idea what is the size_type_Buskets
means so I gave it 1
.
What is the right way to do it?
Thanks.
This is an unfortunate omission in C++11; Boost has the answer in terms of
hash_combine
. Feel free to just paste it from them! Here's how I hash pairs:You can use
hash_combine
as the basis for many other things, like tuples and ranges, so you could hash an entire (ordered) container, for example, as long as each member is individually hashable.Now you can just declare a new map:
If you want to use your homebrew hasher (which hasn't got good statistical properties), you have to specify the template parameters explicitly:
Note that there's no need to specify a copy of a hasher object, as the default is to default-construct one for you.
If you are fine with using Boost, a cleaner solution is to rely on Boost's implementation of the hash function for pairs (which in fact does exactly what kerrek-sb explains in his answer). Therefore all you have to do is:
The return type of the hash function should be
size_t
, notlong
(although this is not the cause of the error). The syntax you've shown for providing a custom hash function is incorrect.You'll also need to provide an equal predicate to make the above work properly.
EDIT:
You don't need to define the equal predicate since
operator==
is defined forstd::pair
and it does exactly what I've done inpairEquals
. You'll only need thepairEquals
definition if you expect the comparison to be done differently.