xml*_*lmx 16 c++ algorithm standards exception
以下程序是使用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!!!
}
Run Code Online (Sandbox Code Playgroud)
如果我return a <= other.a;改为return a < other.a;那么程序按预期运行,没有例外.
为什么?
xor*_*guy 26
std::sort需要一台满足严格弱排序规则的分拣机,这里将对此进行解释
所以,你的比较器说a < b当a == b不遵循严格的弱排序规则时,算法可能会崩溃,因为它会进入无限循环.
Pie*_*aud 10
xorguy的答案非常好.
我只想从标准中添加一些引用:
25.4排序和相关操作[alg.sorting]
对于25.4.3中描述的算法之外的算法无法正常工作,comp必须对值进行严格的弱排序.
术语" 严格"是指对所有x的反自由关系的要求(!comp(x,x)),对于要求的要求不弱于总排序的要求,但强于部分排序的要求.
所以xorguy解释得非常好:你的comp功能说a < b当a == b不遵循严格的弱排序规则时......
| 归档时间: |
|
| 查看次数: |
10005 次 |
| 最近记录: |