0
点赞
收藏
分享

微信扫一扫

std:sort的一次踩坑

林塬 2022-03-22 阅读 94

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永远为真。

举报

相关推荐

0 条评论