以下程序是使用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
的比较器需要严格弱序,而<=
是不符合该要求的。 - WhozCraiga()
(这就是a()
的意思),对于int
类型来说,这意味着0。 - GManNickG