如果比较函数不是运算符<,为什么std::sort会崩溃?

2022-01-08 00:00:00 algorithm exception standards c++

以下程序是用VC++ 2012编译的.

The following program is compiled with VC++ 2012.

#include <algorithm>

struct A
{
    A()
        : a()
    {}

    bool operator <(const A& other) const
    {
        return a <= other.a;
    }

    int a;
};

int main()
{
    A coll[8];
    std::sort(&coll[0], &coll[8]); // Crash!!!
}

如果我将 return a <= other.a; 更改为 return a <other.a; 然后程序按预期运行,没有异常.

If I change return a <= other.a; to return a < other.a; then the program runs as expected with no exception.

为什么?

推荐答案

std::sort 需要一个满足严格弱排序规则的排序器,解释这里

std::sort requires a sorter which satisfies the strict weak ordering rule, which is explained here

所以,你的比较器说 a <ba == b不遵循严格弱排序规则时,算法可能会崩溃,因为它会进入一个无限循环.

So, your comparer says that a < bwhen a == b which doesn't follow the strict weak ordering rule, it is possible that the algorithm will crash because it'll enter in an infinite loop.

相关文章