【发布时间】:2021-11-19 13:42:45
【问题描述】:
以下程序是用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的比较器需要严格的弱排序,<=不提供。 -
你应该为 A ctor 写 a(0)...但它不会在这里崩溃!
-
@LaszloPapp:是的。它对
a()进行值初始化(这就是a()的含义),对于int而言,这意味着0。 -
@LaszloPapp: stackoverflow.com/questions/14259602/…
-
请将未定义行为 &coll[8] 替换为 coll + 8
标签: c++ algorithm exception standards