gpt4 book ai didi

c++ - 如何使 QList 与 indexOf() 和自定义运算符==() 一起工作?

转载 作者:搜寻专家 更新时间:2023-10-31 01:53:49 27 4
gpt4 key购买 nike

给定以下代码:

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() 比较指针。有没有办法在 QList 中保留 ponters 并仍然使用我自己的运算符==()?

Vertex*::operator==(Vertex* other)

相关问题:removing in pointer type Qlists | not working because of pointer type

编辑:意图。

当且仅当,两个顶点被认为是相等的。它们的有效载荷携带的标识符是相等的。

VertexGraph 类的一部分。我希望该类的客户端能够调用 Graph::addEdge(Payload,Payload) 来填充图形。 Graph 对象然后负责将 Payloads 包装在 Vertex 对象中并构建 Edges。因此 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com