【问题标题】:How to make QList<Type*> work with indexOf() and custom operator==()?如何使 QList<Type*> 与 indexOf() 和自定义 operator==() 一起使用?
【发布时间】:2012-05-15 10:26:50
【问题描述】:

给定以下代码:

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() 永远不会调用我的 operator==。我认为这是因为 QList 封装了一个指针类型和 indexOf() 比较指针。有没有办法在 QList 中保留 ponters 并且仍然使用我自己的 operator==()?

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

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

编辑:意图。

两个顶点被认为是相等的。它们的payload携带的标识符是相等的。

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

【问题讨论】:

  • 你不能存储 'QList' 吗?重载 == 不适用于指针。而且,实际上你的代码是行不通的:你构造 new 并尝试在向量中查找它的 adress。不会成功!

标签: c++ qt operator-overloading qlist


【解决方案1】:

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

不,您需要 QList 首先取消引用指针,而事实并非如此。您必须继承 QList 才能做到这一点。但由于 indexOf() 只是迭代并使用 operator==() 进行比较,因此没有什么能阻止您手动执行相同的操作。

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

【讨论】:

  • 非常感谢您的回答@cbamber85。第一部分回答了我的问题并为手头的问题提供了解决方案。我同意代码气味,并且在编码时没有考虑运行时。我会考虑使用更合适的容器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 2020-03-30
相关资源
最近更新 更多