How can I use a C++ unordered_set for a custom class?

daydayup picture daydayup · Jul 24, 2016 · Viewed 10.3k times · Source

How can I store objects of a class in an unordered_set? My program needs to frequently check if an object exists in this unordered_set and if it does, then do some update on that object.

I have looked up online on how to use unordered_set, but sadly most tutorials are about using it on int or string types. But how can I use it on a class? How can I define a hash function to make the node_id in the following example the key of the unordered_set?

#include <iostream>
#include <unordered_set>

using namespace std;

// How can I define a hash function that makes 'node' use 'node_id' as key?    
struct node
{
    string node_id;
    double value;
    node(string id, double val) : node_id(id), value(val) {}
};

int main()
{
    unordered_set<node> set;
    set.insert(node("1001", 100));
    if(set.find("1001") != set.end()) cout << "1001 found" << endl;
}

Answer

sjrowlinson picture sjrowlinson · Jul 24, 2016

You could try using the following hash function object (it's pretty basic so you may want to improve it to avoid too many collisions).

struct node_hash {
    std::size_t operator()(const node& _node) const {
        return std::hash<std::string>()(_node.node_id);
    }
}
// ...
std::unordered_set<node, node_hash> node_set;

However, as one of the comments points out, you may be better off using a std::unordered_map<std::string, double> here.