問(wèn)題描述
以下程序使用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;
然后程序按預(yù)期運(yùn)行,無(wú)一例外.
If I change return a <= other.a;
to return a < other.a;
then the program runs as expected with no exception.
為什么?
推薦答案
std::sort
需要一個(gè)滿足嚴(yán)格弱排序規(guī)則的排序器,具體說(shuō)明這里
std::sort
requires a sorter which satisfies the strict weak ordering rule, which is explained
here
所以,你的比較器說(shuō) a <b
當(dāng)a == b
不遵循嚴(yán)格弱排序規(guī)則時(shí),算法可能會(huì)崩潰,因?yàn)樗鼤?huì)進(jìn)入無(wú)限循環(huán).
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.
這篇關(guān)于如果比較函數(shù)不是運(yùn)算符 <,為什么 std::sort 會(huì)崩潰?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!