C++ unordered_map using a custom class type as the key

前端 未结 4 1054
梦如初夏
梦如初夏 2020-11-21 23:32

I am trying to use a custom class as key for an unordered_map, like the following:

#include 
#include 
#include         


        
4条回答
  •  长发绾君心
    2020-11-22 00:36

    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:

    1. You can define a comparison function for an 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.
    2. You can also use lambda expressions instead of defining the hash and comparison functions.

    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:

    • I just reused the hashing method at the end of jogojapan's answer, but you can find the idea for a more general solution here (if you don't want to use Boost).
    • My code is maybe a bit too minified. For a slightly more readable version, please see this code on Ideone.

提交回复
热议问题