标准重载运算符<:设置(英语:SET)

Overloading Operator < for std::set

本文关键字:设置 SET 英语 重载 运算符 lt 标准      更新时间:2023-10-16

我有一个名为Dist的结构,

struct Dist {
    Point firstPoint, secondPoint;
    double value;
};
struct distCompare {
    bool operator()(const Dist& x, const Dist& y) const {
        return x.value < y.value;
    }
};

并且我有一个集合来存储这个Object。

std::set<Dist, distCompare> distList;

如果x.firstPoint==y.firstPoint and x.secondPoint==y.secondPoint,像x和y这样的两个Dist是相等的由于distCompare比较两个Dist的值,我不能像这样使用set::find

for (auto q:input) {
    Dist tempDist; tempDist.firstPoint = p; tempDist.secondPoint = q;
    auto it = distList.find(tempDist);
    if (it != distList.end()) { //'it' is always distList.end() 
        distList.erase(it); 
    }
}

我的Point类看起来是这样的:

class Point {
public:
    Point(double a, double b){ x = a; y = b; }
    Point(){}
    double getX() const { return x; }
    double getY() const { return y; }
    void setX(double item){ x = item; }
    void setY(double item){ y = item; }
private:
    double x, y;
};

如何使运算符<以便我可以使用set::find来找到相等的Dists?

std::set<T, Cmp>::find进行二进制搜索,这取决于元素是有序的,并且总是使用Cmp来决定等价性(这与等式不同),所以如果你不想让它基于distCompare来查找。。。那么不要在集合中使用distCompare

由于distCompare定义的排序与您对Dist对象相等的定义完全无关,因此无法使用distCompare排序执行快速二进制搜索,以查找被完全不同的函数认为相等的对象。根据相等的定义,可以有两个"相等"的元素,但根据distCompare定义的顺序,它们在集合的两端排序。

您的选择是:

  • 更改集合的比较函数,以便比较相等的项也可以使用比较函数比较相等项。

  • 将集合替换为多索引容器,如Boost.MultiIndex.

  • 通过设置的执行线性搜索