部分排序数组,最后n个元素排序
Partially sorting array so last n elements are sorted?
是否有一种方法对数据数组执行部分排序,以便对最后n个元素进行排序?我说的好是指使用标准库,而不是实现我自己的排序函数(这就是我现在正在做的)。示例输出(使用less comparator):
2 1 4 || 5 6 8 10
||
之后的元素都大于||
之前的元素,但只有||
右边的元素(靠近数组末尾的索引)才保证被排序。
这基本上是对左(第一个)元素排序的std::partial_sort函数的反转。
使用std::partial_sort
逆迭代器
int x[20];
std::iota(std::begin(x), std::end(x), 0);
std::random_shuffle(std::begin(x), std::end(x));
std::reverse_iterator<int*> b(std::end(x)),
e(std::begin(x));
std::partial_sort(b, b+10, e, std::greater<int>());
for (auto i : x)
std::cout << i << ' ';
另一种可能性是使用std::nth_element
对集合进行分区,然后使用std::sort对您关心的分区进行排序,而不是使用反向迭代器partial_sort
和std::greater进行比较:
std::vector<int> data{5, 2, 1, 6, 4, 8, 10}; // your data, shuffled
std::nth_element(data.begin(), data.begin()+2, data.end());
std::sort(data.begin()+2, data.end();
在c++20中使用范围和视图是非常简单的。
数组的例子:
//DATA
int arrayOfInts[8] = { 82,80,81,86,83,85,84,88 };
//SORT LAST 5 ELEMENTS. SO DROP FIRST 3.
std::ranges::sort(std::views::drop(arrayOfInts, 3));
//PRINT ARRAY -- 82 80 81 || 83 84 85 86 88
for (auto i : arrayOfInts)
std::cout << i << " ";
向量的例子://DATA
std::vector<int> vecOfInts = { 82,80,81,86,83,85,84,88 };
//SORT LAST 5 ELEMENTS. SO DROP FIRST 3.
std::ranges::sort(std::views::drop(vecOfInts, 3));
//PRINT VECTOR -- 82 80 81 || 83 84 85 86 88
for (auto i : vecOfInts)
std::cout << i << " ";
相关文章:
- 二叉排序树无法编译
- 读取文件的最后一行并输入到链接列表时出错
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- lower_bound()返回最后一个元素
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 修改的选择排序,选择最大的数字,然后交换到最后
- 排序<cr>时应最后出现与 '' 的字符串
- C++:对数组进行排序,最后一个数字重复两次
- 排序为最后一个位置的元素提供错误的输出
- 合并排序程序总是有效的,但有时会在最后说中止陷阱
- QAbstractTableModel最后一行为空,不进行排序
- 我需要创建一个函数,它接受字符串的矢量,然后按最后一个字母对它们进行排序
- 冒泡排序不排序最后一个数字与此算法
- 排序程序仅显示第一个和最后一个数字
- 部分排序数组,最后n个元素排序