Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert custom class into unordered_map c++

I have a problem which probably has a simple solution but I have looked around for a while and still no success.

I have a simple class as follows:

class Node{
public:
int value;
bool visited;
Node(int argvalue) {value = argvalue;visited = false; }
bool operator==(const Node& n) {return (value == n.value);}
};

class MyHash {
size_t operator()(const Node& x) const { return std::hash<int>()(x.value); }
};

Now when I try to insert I get error and can not understand why? Did I implement my hash-function incorrectly or is the equal operator == not sufficient?

unordered_map<Node, int, MyHash> my_items;
my_items.insert(Node(33), 894);
like image 883
Euklides Avatar asked Nov 30 '25 08:11

Euklides


1 Answers

None of the two-parameter insert methods matches insert(key_type, mapped_type), which is what you are attempting.

The map holds std::pair<const Key, T>, so you need to insert a pair, either explicitly:

my_items.insert(std::make_pair(Node(33), 894));

or using brace initialization:

my_items.insert({Node(33), 894});

You could use the std::unordered_map::emplace member function, which allows you to pass the constructor arguments of a pair:

my_items.emplace(Node(33), 894);

Other things:

  • bool Node::operator== should be const (a comparison should not change the objects being compared)
  • size_t MyHash::operator()(...) const should be public.
like image 176
juanchopanza Avatar answered Dec 02 '25 21:12

juanchopanza