繁体   English   中英

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

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

下面的程序是用 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需要一个满足严格弱排序规则的std::sort器,这里解释

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

xorguy 的答案非常好。

我只想从标准中添加一些引用:

25.4 排序及相关操作 [alg.sorting]

为了使 25.4.3 中描述的算法以外的算法正常工作, comp 必须对值进行严格的弱排序

严格指的是反自反关系的要求(!comp(x, x) for all x),指的要求不如全序强,但强于偏序.

所以 xorguy 解释得很好:你的comp函数说a < ba == b不遵循严格的弱排序规则......

您的代码的问题在于您正在访问无效的内存。 代码

coll[8]

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

std::array<A, 8> a;

// fill it somehow

std::sort(a.begin(), a.end());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM