Reputation: 782
My operator == is not beeing called when i use QList or QHashMap
here is my code :
class Node
{
QString _state;
Node* _parent;
// for ID generation purpose
static int _seqNumber;
int _id;
public:
Node();
inline bool operator== (const Node &node) const
{
return ( _id == node._id );
}
}
Now if i use QHash for example :
QHash<Node*, double> hashMap* = new QHash<Node*, double>();
Node* node = new Node();
hashMap->insert(node, 500);
// value is never found, because operator== is not being called
double value = hashMap->value(node);
I can't get value or compare is node exists in the map because operator== is not called !!
If you can help i would apreciate that.
Upvotes: 1
Views: 1617
Reputation: 1256
The Hash key is a pointer(Node*
) not a Node
object. so the map or hash is comparing pointers in there. Thus, there's really no need to your operator==
.
And you cannot ask compiler to use your function to compare two pointers. because a pointer is a primitive type just like an int
. you cannot overload operator==
to compare two int
s.
So, I think the solution, could be to use your object as hash key like this:
QHash<Node, double> //[1]
or just use pointer and leave the comparison to pointer comparisons.
[1] But then, you'd have to provide a hash function for the QHash
to work as well.
Upvotes: 0
Reputation: 39099
This is expected behaviour. You are using Node*
as your key-type, but there is no special operator==(Node*,Node*)
defined.
What you seem to intend is Node
.
Upvotes: 5