Reputation: 584
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);
Upvotes: 2
Views: 9878
Reputation: 227418
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.Upvotes: 10
Reputation: 26040
You have a couple of errors. Firstly, operator()
is private
in MyHash
since it is a class and default access for classes is private. Either mark it as public
or change it to struct MyHash
.
Secondly, you cannot insert values like that. It will need to be something like my_items.insert(std::make_pair(Node(33), 894))
;
Upvotes: 0