Why will std::sort crash if the comparison function is not as operator lt;?(如果比较函数不是运算符 lt;,为什么 std::sort 会崩溃?)
问题描述
以下程序使用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; 然后程序按预期运行,无一例外.
If I change return a <= other.a; to return a < other.a; then the program runs as expected with no exception.
为什么?
推荐答案
std::sort 需要一个满足严格弱排序规则的排序器,具体说明这里
std::sort requires a sorter which satisfies the strict weak ordering rule, which is explained
here
所以,你的比较器说 a <b当a == b不遵循严格弱排序规则时,算法可能会崩溃,因为它会进入无限循环.
So, your comparer says that a < bwhen 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.
这篇关于如果比较函数不是运算符 <,为什么 std::sort 会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果比较函数不是运算符 <,为什么 std::s
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
