【发布时间】: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 在这些情况下是如何工作的?
【问题讨论】: