以下程序使用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 会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在 Visual Studio 2008 中为我的应用程序设置图标How do I set the icon for my application in visual studio 2008?(如何在 Visual Studio 2008 中为我的应用程序设置图标?)
将 CString 转换为 const char*Convert CString to const char*(将 CString 转换为 const char*)
默认情况下,在 Visual Studio 中从项目中删除安全Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio(默认情况下,在 Visual Studio 中从项目中删除安全
如何在 Visual Studio 2008 中启动新的 CUDA 项目?How do I start a new CUDA project in Visual Studio 2008?(如何在 Visual Studio 2008 中启动新的 CUDA 项目?)
从 DLL 导出包含 `std::` 对象(向量、映射等)的类Exporting classes containing `std::` objects (vector, map etc.) from a DLL(从 DLL 导出包含 `std::` 对象(向量、映射等)的类)
发布版本与调试版本的运行方式不同的一些原因What are some reasons a Release build would run differently than a Debug build(发布版本与调试版本的运行方式不同的一些原因是什么