std:sort的一次踩坑

C++ sort中cmp的一个问题

在写自定义比较函数的时候,如果两个元素相等,一定要返回false,否则很有可能会产生越界问题。

sort

关于sort的解析,可以参考std::sort源码剖析
源码里的划分函数 __unguarded_partition :

  template<typename _RandomAccessIterator, typename _Compare>
    _RandomAccessIterator
    __unguarded_partition(_RandomAccessIterator __first,
			  _RandomAccessIterator __last,
			  _RandomAccessIterator __pivot, _Compare __comp)
    {
      while (true)
	{
	  while (__comp(__first, __pivot))
	    ++__first;
	  --__last;
	  while (__comp(__pivot, __last))
	    --__last;
	  if (!(__first < __last))
	    return __first;
	  std::iter_swap(__first, __last);
	  ++__first;
	}
    }

可以看到,在移动first时,不会检查越界问题,因为pivot是一个median的值,也就是整个数组中一定有大于等于它的值,让移动first的这个while停止,这样可以省去很多越界判断的语句。
我自己写的一个cmp函数,将相等时的返回值写成了true。这就导致当数组中元素全部相等的时候,first会越界,因为第一个while永远为真。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值