std::sort 如何处理重复的数字?

How does std::sort work with duplicated numbers?

本文关键字:数字 sort 何处理 std 处理      更新时间:2023-10-16

当我测试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");
}

当我没有将包括 <= 在内的 lambda 表达式传输到 std::sort 时,一切都很顺利。然而,当我真正这样做时,各种例外出现了。在这种情况下,发生了分段错误。有时编译器无法删除 vector 中的元素。

经过彻底检查,我发现 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时,该陈述始终是正确的,因此我们不知道__first去哪里。

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

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

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

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