您的位置:首页 > 编程语言 > C语言/C++

c++排序的一个问题

2015-01-22 11:40 246 查看
开发的服务器在更新资料片后,出现了大量服务器随机崩溃的情况,经过排查问题,终于找到,

这里和大家分享一下。

首先分析错误堆栈,发现随机崩溃,怀疑是内存被覆盖,只好回头研究资料片代码,发现一个sorter的实现如下:

struct SORTER
{
bool operator()(const OBJID& idLeft, const OBJID& idRight)
{
return RandGet(100) > 50;
}
}


因为要求实现排序最后需要随机排序。所以最后脑洞大开使用随机返回的代码。

而问题就出在这里,因为std::sort要求的是严格偏序,要求相等的对象必须返回false。

http://www.cplusplus.com/reference/algorithm/sort/

comp
Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.


而这种实现,会导致在排序过程中,对于确定相等的2个数据,在比较时会返回不同的结果,造成内存覆盖,从而导致随机崩溃。

而实际上,std::sort本身就不是稳定排序,意味着,相同的2个对象,就是会随机排序的,所以如果要稳定排序,那么要用stable_sort

修改为:

struct SORTER
{
bool operator()(const OBJID& idLeft, const OBJID& idRight)
{
return false;
}
}


问题解决了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: