【问题标题】:How does std::sort work with duplicated numbers? [duplicate]std::sort 如何处理重复的数字? [复制]
【发布时间】:2020-05-02 20:24:06
【问题描述】:

当我测试 std::sort 函数来处理一个充满重复数字的向量时,我发现了一些非常令人困惑的东西。

例如,这里有一段c++代码。

#include <ctime>
#define startTime std::clock_t stTime = clock()
#define endTime std::clock_t edTime = clock()
#define processTime static_cast<double>(edTime - stTime) / CLOCKS_PER_SEC
#include <bits/stdc++.h>
using namespace std;
int main() {
    int i = 0;
    vector<int> v;
    while (i != 1000000) {
        v.push_back(2);
        ++i;
    }
    startTime;
    sort(begin(v), end(v), [](const int& lhs, const int& rhs) { return lhs <= rhs; });
    endTime;
    cout << processTime;
    system("pause");
}

当我没有将包含

经过仔细检查,我发现 STL 文件中可能发生了一些事情:

//stl_algo.h
  /// This is a helper function...
  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;
    }
    }

__pivot__first+1

在比较 __first__pivot 时,声明总是true,所以我们不知道 __first 去了哪里。

谁能解释 std::sort 在这些情况下是如何工作的?

【问题讨论】:

    标签: c++ algorithm sorting stl


    【解决方案1】:

    您使用 lambda 创建了无效的比较器函数,应该使用 &lt; 而不是 &lt;=,否则 sort() 会不断交换相等的元素。

    根据sort 的参考,比较器必须:

    比较函数对象(即满足比较要求的对象)如果第一个参数小于(即排序在)第二个参数,则返回​true

    【讨论】:

      猜你喜欢
      • 2020-09-14
      • 2016-08-29
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      相关资源
      最近更新 更多