C++ sort之Segmentation fault原因及其解决方法

写sort的比较函数时要符合给定的要求,否则可能会出现Segmentation fault异常。

文档上对比较函数的要求:

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.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.

如果比较函数返回真,则表示第一个参数会排在第二个参数前面。
strict weak ordering的含义是:

For all a, comp(a, a) == false
If comp(a, b) == true then comp(b, a) == false
if comp(a, b) == true and comp(b, c) == true then comp(a, c) == true

所以,比较函数不能写成:

bool cmp(int a, int b){
    return a <= b;
}

为什么呢?比较函数写成以上那样,当a和b相同时,会返回true。此时比较元素会一直遍历下去,当所有元素都是相同的情况下,就会出现访问越界,导致Segmentation fault。

解决方法:

bool cmp(int a, int b){
    return a < b;
}

这样使得a和b相等的时候返回false。

参考文档:
1. C++ Sort Segmentation Fault
2. sort function C++ segmentation fault
3. Why does std::sort throw a segmentation fault on this code?
4. std::sort 排序vector 崩溃原因
5. std::sort

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值