c++ - std::set 和 < 运算符重载的奇怪行为?

标签 c++ algorithm sorting c++11 set

我明白如果<运算符在 C++ 中重载(例如,将自定义结构插入 std::set ),实现必须是 strict weak order在底层类型上。

考虑以下 struct和实现。此实现不是严格的弱顺序,但代码编译和运行时不会抛出错误(考虑到严格的弱顺序的要求,我希望它会抛出错误):

#include <iostream>
#include <set>
using namespace std;

struct Pixel {
    int x;
    int y;
};

bool operator < (Pixel lhs, Pixel rhs){
    return lhs.x < rhs.x || lhs.y < rhs.y;
};

int main(){
    set<Pixel> mySet;

    Pixel *newPixelA = new Pixel;
    newPixelA->x = 1;
    newPixelA->y = 3;

    Pixel *newPixelB = new Pixel;
    newPixelB->x = 4;
    newPixelB->y = 2;

    mySet.insert(*newPixelA);
    mySet.insert(*newPixelB);

}

这是预期的行为吗?编辑:使用 Xcode。

最佳答案

编译器无法确定您的 operator< 是否正确。是一个严格的弱排序。相反,std::set 是什么意思?要求这是只有在你给它一个严格的弱排序时它才能正常工作。它不保证如果你给它其他东西会发生什么。

一般来说,当 C++ 需要某事时,它的意思是确保某事发生是的责任。如果这样做,编译器和库将保证您获得正确的结果。

关于c++ - std::set 和 < 运算符重载的奇怪行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47007924/

相关文章:

c - 在c中排序双向链表

c++ - 为什么 std::string 不能成为 '...' 之前的最后一个命名参数?

algorithm - 为什么选择算法的运行时间是 O(n)?

C++:模板特化,std 映射选择了错误的特化

algorithm - 如何在多个条件下选择项目

algorithm - 查找最大堆中第k个元素的位置

bash - 按整数值排序

java - 在线性 (O(N)) 时间内对数组进行排序

c++ - 应该问什么问题来测试面试候选人对 C++ 引用资料的了解?

c++ - 如何检测 C++ 中有符号和无符号整数的错误减法?