Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何制作QList<;类型*>;使用indexOf()和自定义运算符==()?_C++_Qt_Operator Overloading_Qlist - Fatal编程技术网

C++ 如何制作QList<;类型*>;使用indexOf()和自定义运算符==()?

C++ 如何制作QList<;类型*>;使用indexOf()和自定义运算符==()?,c++,qt,operator-overloading,qlist,C++,Qt,Operator Overloading,Qlist,给定以下代码: 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

给定以下代码:

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
}
QList\u顶点//这个被填满了
//在另一点上,我想检查是否已经有
//列表中具有相同负载的顶点
顶点*v=新顶点(有效载荷);
int结果=_顶点.indexOf(v);
如果(结果==-1){
//将顶点添加到列表中
}否则{
//放弃v并返回匹配的指针
}
//重载顶点::运算符==
布尔顶点::运算符==(顶点*其他){
//如果我的有效载荷和其他有效载荷
//有效载荷是相同的
}
就我所知,indexOf()永远不会调用我的运算符==。我假设这是因为QList封装了指针类型,而indexOf()比较了指针。是否有一种方法可以将ponters保留在QList中,并且仍然使用我自己的运算符==()

顶点*::操作符==(顶点*其他)

相关问题:|

编辑:意图

两个顶点视为相等。有效载荷携带的标识符是相等的

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

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

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


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

您不能存储“QList”吗?重载==对指针不起作用。而且,实际上您的代码都不起作用:您构建新的,并尝试在vector中查找它的地址。不会成功的!非常感谢您的回答@cbamber85。第一部分回答了我的问题,并为当前的问题提供了解决方案。我同意代码的气味,在编码时没有考虑运行时间。我会考虑使用更合适的容器。