c ++ std :: set equality

use*_*477 7 c++ compare equals set

我尝试使用a std::set以便在容器中包含唯一元素.

由于我有3D对象:

Class Object3D{  
 private:  
  float x;  
  float y;  
  float z;  
}
Run Code Online (Sandbox Code Playgroud)

那些对象在等于 (A.x==B.x && A.y==B.y && A.z==B.z).
在std :: set实现中有一个元素 A==B if (!(A < B) && !(B>A)).
我的比较是不可能的...我试图超载==运算符.
我选择set container来比较我打电话时的值insert(a).我std::vector v和他的迭代器做了类似的事情:

if(!(A).inVector()){
 v.push_back(A);
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

检查每个对象(10000-100000)的复杂性是昂贵的.
有人有想法吗?

Ker*_* SB 7

您需要<为您的班级实施严格的弱排序.最简单的方法是使用以下提供的词典排序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);
    }

    // ...
};
Run Code Online (Sandbox Code Playgroud)

  • 很好用`领带'. (2认同)

Use*_*ess 5

@OP:std::set是一个独特的、有序的容器。它需要operator<显式传递an或比较器,这实现了严格的弱排序。

如果您不想对元素进行排序,请不要使用有序容器。std::unordered_set如果您只想检测唯一性而不强制排序,则可以使用。


sla*_*ppy 1

必须提供一个比较运算符,因为std::set需要它来实现。

一个简单的小于运算符如下所示:

bool Object3D::operator<(const Object3D& other) const {
    if(x != other.x) return x < other.x;
    if(y != other.y) return y < other.y;
    return z < other.z;
}
Run Code Online (Sandbox Code Playgroud)