给出以下代码:
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
}
据我所知,indexOf() 永远不会最终调用我的运算符==。我认为这是因为 QList 封装了指针类型并且 indexOf() 比较了指针。有没有办法将 ponters 保留在 QList 中并仍然使用我自己的运算符 ==()?
像Vertex*::operator==(Vertex* other)
相关问题:removing in pointer type Qlists | not working because of pointer type
编辑:意图。
两个顶点被视为相等当且仅当。其有效负载携带的标识符是相等的。
Vertex
是 Graph
类的一部分。我希望该类的客户端能够调用 Graph::addEdge(Payload,Payload) 来填充图表。然后,图对象负责将有效负载包装在顶点对象中并构建边。因此,Graph 需要检查封装给定有效负载的 Vertex 是否尚不存在。在编写代码时,使用 QList 似乎是“可能有效的最简单的方法”。
最佳答案
Is there a way of keeping ponters in the QList and still using my own operator==()?
不,您需要 QList 首先取消引用指针,但事实并非如此。为了做到这一点,你必须子类化 QList。但由于 indexOf()
只是使用 operator==()
进行迭代和比较,因此没有什么可以阻止您手动执行相同的操作。
但是,所有这些看起来都像是代码味道。尝试在无序/非哈希容器中查找某些内容是线性时间 - 与 QMap/QHash 相比非常慢。请编辑您的问题,描述您为什么要这样做,以及 Vertex 包含哪些数据,我们将看看社区是否可以提供更好的执行机制。
关于c++ - 如何使 QList<Type*> 与 indexOf() 和自定义运算符 ==() 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10598768/