gpt4 book ai didi

C++ std::set 相等性

转载 作者:可可西里 更新时间:2023-11-01 18:17:45 26 4
gpt4 key购买 nike

我尝试使用 std::set为了在我的容器中有独特的元素。

因为我有 3D 对象:

Class Object3D{  
private:
float x;
float y;
float z;
}

(A.x==B.x && A.y==B.y && A.z==B.z) 时,这些对象相等.
在 std::set 实现中,一个元素 A==B if (!(A < B) && !(B>A)) .
我的比较是不可能的......我试图重载==运算符。
当我调用 insert(a) 时,我选择了设置容器来比较值.我正在用 std::vector v 做类似的事情和他的迭代器:

if(!(A).inVector()){
v.push_back(A);
}

bool inVector(){
for(itr = v.begin();itr != v.end();itr++){
if(this->x==(*itr)->x && this->y==(*itr)->y && this->z==(*itr)->z){
return true;
}
}
return false;
}

检查每个对象 (10000-100000) 的复杂性很高。
有人可以有想法吗?

最佳答案

您需要实现严格的弱排序 <为你的类(class)。最简单的方法是使用 tuple 提供的字典顺序:

#include <tuple>

class Object3D
{
public:
bool operator<(Object3D const & rhs) const
{
return std::tie(x, y, z) < std::tie(rhs.x, rhs.y, rhs.z);
}

// ...
};

关于C++ std::set 相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13158682/

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