So, I’m trying to check whether a particular object is already present in the set. For this, I use the count() method. Now, it doesn’t seem to return the right answer. Let me explain the problem a bit more clearly —
I have declared a class this way
class Node{
public:
Node(int _state=0, int _cost=0)
{
state = _state;
cost = _cost;
}
bool operator<(const Node& rhs)
{
return cost < rhs.cost;
}
bool operator==(const Node& rhs)
{
cout << "== operator method used" << endl;
if (rhs.state == state)
return true;
return false;
}
int state;
int cost;
};
in my code, I declare a set like this —
set<Node*> myset;
after a few insertions, myset is like this {{1, 5}, {2, 6}, {3, 9}}
now I check whether {1, 7} is part of the set. How would it do it? I have written a operator== method in Node class, which is never called. Then on what basis does count() check if the object is already in the set?… I would want the count to work in a fashion that if {1, 5} is already there in myset, it should view {1, 7} as a duplicate entry.
It uses
operator<by default.In fact, in general, C++ Standard Library containers use
!(a < b) && !(b < a)to determine the property of equivalence.You can override the comparator used to perform this check by providing your own
Comparetemplate argument to the container type, though there is rarely a reason to — you should usually simply defineoperator<for your type instead, as you have done. (Make sure that it creates a Strict Weak Ordering, though.)No, your set is never like this. Your set contains pointers, not
Nodes. Make it aset<Node>instead.