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

Why will std::sort crash if the comparison function is not as operator <?

本文关键字:为什么 std sort 崩溃 lt 函数 比较 运算符 如果      更新时间:2023-10-16

下面的程序是用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;,那么程序将按预期运行,无一例外。

为什么?

std::sort需要一个满足严格弱排序规则的分类器此处

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

xorguy的答案非常好。

我只想添加一些来自标准的报价:

25.4排序和相关操作[算法排序]

为了使25.4.3中描述的算法以外的算法正确工作,comp必须在值上引入严格的弱排序

术语strict指的是不可伸缩关系(!comp(x,x)对于所有x)的要求,而术语weak则指的是那些不如全序强,但比偏序强的要求。

所以xorguy很好地解释了这一点:当a == b不遵循严格弱排序规则时,comp函数说a < b。。。

代码的问题是访问无效内存。代码

coll[8]

尝试访问最后一个数组元素之后的元素(最后一个元素索引为7)。我建议使用std::array,而不是普通的C数组。

std::array<A, 8> a;
// fill it somehow
std::sort(a.begin(), a.end());