I am trying to use a custom class as key for an unordered_map
, like the following:
#include
#include
#include
I think, jogojapan gave an very good and exhaustive answer. You definitively should take a look at it before reading my post. However, I'd like to add the following:
unordered_map
separately, instead of using the equality comparison operator (operator==
). This might be helpful, for example, if you want to use the latter for comparing all members of two Node
objects to each other, but only some specific members as key of an unordered_map
.All in all, for your Node
class, the code could be written as follows:
using h = std::hash;
auto hash = [](const Node& n){return ((17 * 31 + h()(n.a)) * 31 + h()(n.b)) * 31 + h()(n.c);};
auto equal = [](const Node& l, const Node& r){return l.a == r.a && l.b == r.b && l.c == r.c;};
std::unordered_map m(8, hash, equal);
Notes: