如何使 QList<Type*> 与 indexOf() 和自定义运算符==()一起使用?

How to make QList<Type*> work with indexOf() and custom operator==()?

本文关键字:自定义 一起 运算符 indexOf lt QList 何使 Type gt      更新时间:2023-10-16

给定以下代码:

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)

相关问题:在指针类型中删除 Qlist | 由于指针类型而不起作用

编辑:意图。

两个顶点被认为是相等的,其有效载荷携带的标识符是相等的。

VertexGraph类的一部分。我希望该类的客户端能够调用Graph::addEdge(Payload,Payload)来填充图形。然后,图形对象负责在顶点对象中包装有效负载并构建边。因此,Graph 需要检查封装给定有效负载的顶点是否还不存在。在编写代码时,使用 QList 似乎是"可能工作的最简单的事情"。

有没有办法将 ponters 保留在 QList 中并仍然使用我自己的 运算符==()?

不,您需要 QList 首先取消引用指针,但它没有。 您必须对QList进行子类才能做到这一点。 但是,由于indexOf()只是使用operator==()进行迭代和比较,因此没有什么可以阻止您手动执行相同的操作。

但是,所有这些看起来都像是代码气味。 尝试在无序/非哈希容器中查找某些内容是线性时间 - 与QMap/QHash相比非常慢。 请编辑您的问题,描述您为什么要这样做,以及Vertex包含哪些数据,我们将看看社区是否可以采用更好的执行机制。