I’m using a std::unordered_set for the first time and have a question about the hash function. As far as I understand, if you don’t specify a hash function it will default to std::hash<Key>.
I have a mySet member in one of my classes:
typedef std::unordered_set<MyClass> USetType;
USetType mySet;
When I try to build, I get the following error:
error C2440: ‘type cast’ : cannot convert from ‘const MyClass’ to ‘size_t’
Is it necessary to define a conversion function (to size_t) if you want to use unordered_set with a custom class? Is there any way to avoid writing your own hash function and just using the default?
If you don’t specify your own hash functor as template argument, it will default to
std::hash<MyClass>, which does not exist unless you define it.Best define your own specialization of
std::hashinside namespacestd:And make sure you include this code before the declaration of your hash. This way you can declare the hash simply as
std::unordered_set<MyClass>with no need for further template arguments.You didn’t specify what
MyClasslooks like inside, but a typical situation is that your user-defined type simply consists of several simple-type members, for which a default hash function exists. In this case, you will probably want to combine the hash values for the individual types to a hash value for the entire combination. The Boost library provides a function calledhash_combinefor this purpose. Of course, there is no guarantee that it will work well in your particular case (it depends on the distribution of data values and the likelihood of collisions), but it provides a good and easy-to-use starting point.Here is an example of how to use it, assuming
MyClassconsists of two string members: