std::sort 如何处理重复的数字?
How does std::sort work with duplicated numbers?
当我测试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。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 为什么 std::unique 不调用 std::sort?
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 对字符串进行排序时,在c++中处理sort()
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- std::sort 如何处理重复的数字?
- sort() 方法 c++ 中的比较器函数.为大量数字获得不同的解决方案
- QUICK SORT堆栈溢出c++大数字