栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

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

  template
    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
    _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;
    }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/665169.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号