为什么标准::排序崩溃,如果比较的功能并不像运营商LT ;? [英] Why will std::sort crash if the comparison function is not as operator <?
本文介绍了为什么标准::排序崩溃,如果比较的功能并不像运营商LT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的程序编译与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!!!
}
如果我修改返回&LT; = other.a;
到返回&LT; other.a;
然后程序运行正常,没有异常
If I change return a <= other.a;
to return a < other.a;
then the program runs as expected with no exception.
为什么?
推荐答案
的std ::排序
要求分拣机满足在严格弱序规则,解释
这里
std::sort
requires a sorter which satisfies the strict weak ordering rule, which is explained
here
那么,你的比较器说, A&LT; b
在 A == b
不遵循严格弱序规则,它有可能是算法会崩溃,因为它会在一个无限循环进入。
So, your comparer says that a < b
when 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.
这篇关于为什么标准::排序崩溃,如果比较的功能并不像运营商LT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文