c++ sort 函数comparator的注意事项

这篇博客深入解析了C++标准库中的排序算法,特别是快速排序中的__unguarded_partition函数。该函数在处理相等元素时,若返回true可能导致边界问题。博客介绍了C++sort的实现细节,包括插入排序、堆排序和快速排序,并重点分析了三数取中策略在pivot选择中的作用,以及如何避免因相等元素导致的越界风险。此外,还展示了部分源代码以辅助理解算法的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. comparator 的签名必须为
 bool cmp(const Type1 &a, const Type2 &b)
  1. 对于相等的值永远返回 false

对于第二点可能有些难以理解,下面将进行详细解释
c++ sort 的实现非常厉害, 里面包括了插入排序, 堆排序,快排等等各种排序。

在快速排序的时候piovt 使用的是三数取中的方式
在__unguarded_partition函数,如果相等值返回 true的话, 那么这个函数可能会出现越界情况
在这里插入图片描述

  template<typename _RandomAccessIterator, typename _Size>
    void
    __introsort_loop(_RandomAccessIterator __first,
             _RandomAccessIterator __last,
             _Size __depth_limit)
    {
      typedef typename iterator_traits<_RandomAccessIterator>::value_type
    _ValueType;

      while (__last - __first > int(_S_threshold))
    {
      if (__depth_limit == 0)
        {
          std::partial_sort(__first, __last, __last);
          return;
        }
      --__depth_limit;
      _RandomAccessIterator __cut =
        std::__unguarded_partition(__first, __last,
    
    // 三数取中                   _ValueType(std::__median(*__first,
                                *(__first
                                  + (__last
                                     - __first)
                                  / 2),
                                *(__last
                                  - 1))));
      std::__introsort_loop(__cut, __last, __depth_limit);
      __last = __cut;
    }
    }


  template<typename _RandomAccessIterator, typename _Tp>
    _RandomAccessIterator
    __unguarded_partition(_RandomAccessIterator __first,
              _RandomAccessIterator __last, _Tp __pivot)
    {
      while (true)
    {
    // 如果 first 到 pivot 一直相等
    // 那么 会存在first越界的问题
      while (*__first < __pivot)
        ++__first;
      --__last;
      while (__pivot < *__last)
        --__last;
      if (!(__first < __last))
        return __first;
      std::iter_swap(__first, __last);
      ++__first;
    }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值