Given the following code:
QList<Vertex*> _vertices; //this gets filled
//at some other point i want to check if there's already
//a vertex with the same payload inside the list
Vertex* v = new Vertex(payload);
int result = _vertices.indexOf(v);
if (result == -1){
//add the vertex to the list
} else {
//discard v and return pointer to match
}
//overloaded Vertex::operator==
bool Vertex::operator==(Vertex* other){
//i return true if my payload and the others
//payload are the same
}
As far as I can see indexOf() never ends up calling my operator==. I assume this is because of QList encapsulating a pointer type and indexOf() comparing the pointers. Is there a way of keeping ponters in the QList and still using my own operator==()?
Like Vertex*::operator==(Vertex* other)
Related Questions: removing in pointer type Qlists | not working because of pointer type
Edit: Intention.
Two vertices are considered equal iff. identifiers carried by their payload are equal.
Vertex
is part of a Graph
class. I want clients of that class to be able to call Graph::addEdge(Payload,Payload)
to populate the graph. Graph objects then take care of wrapping up Payloads in Vertex objects and building Edges. Hence Graph needs to check if a Vertex encapsulating a given payload doesn't already exist. Using QList seemed like the "simplest thing that might work" at the time of writing the code.
Is there a way of keeping ponters in the QList and still using my own operator==()?
No, you would need QList to dereference the pointer first, which it doesn't. You would have to subclass QList in order to do that. But as indexOf()
just iterates through and compares using operator==()
there's nothing stopping you doing the same thing manually.
However, all of this looks like a code smell. Trying to find something in an unordered/non-hashed container is in linear time - very slow compared to QMap/QHash. Please edit your question describing why you want to do this, and what data Vertex
contains, and we'll see if the community can up with better performing mechanism.