以下程序是使用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;
那么程序按预期运行,没有例外。
为什么?
发布于 2019-02-21 14:34:26
std::sort
需要一台满足严格弱排序规则的分拣机,这里将对其进行解释
所以,你的比较器说a < b
当a == b
不遵循严格的弱排序规则时,算法可能会崩溃,因为它会进入无限循环。
发布于 2019-02-21 16:13:45
xorguy的答案非常好。
我只想从标准中添加一些引用:
25.4排序和相关操作[alg.sorting] 对于25.4.3中描述的算法之外的算法无法正常工作,comp必须对值进行严格的弱排序。 术语“ 严格”是指对所有x的反自由关系的要求(!comp(x,x)),对于要求的要求不弱于总排序的要求,但强于部分排序的要求。
所以xorguy解释得非常好:你的comp
功能说a < b
当a == b
不遵循严格的弱排序规则时......
https://stackoverflow.com/questions/-100005159
复制相似问题