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);
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With