从容器中提取N个最高元素
C++: Extract N highest elements from container
我经常需要从未排序的STL容器中提取N(> 1)个最高元素。最简单的方法是使用<queue>
。
是否有更快,更少的样板方式?
获取n
最小元素,使用nth_element
:
std::vector<int> v = { 2, 6, 1, 13, 51, 5, 0, -1 };
std::nth_element(v.begin(), v.begin() + 3, v.end());
// now v[0], v[1], v[2] are the smallest, not otherwise sorted
确保#include <algorithm>
。可以提供一个可选谓词来定制排序顺序(例如std::greater<int>
)。
std::partial_sort
如果你需要它们的顺序,否则std::nth_element
,使用greater
作为你的谓词在任何情况下
我不能告诉如果提取你的意思是你想要删除,但如果你这样做,那么另一个选项是堆积你的容器与make_heap
,然后拔出N
元素。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- C++:矩阵高斯消除不起作用:使用单维数组来存储元素
- 使用 C++17 或更高版本对向量中的元素对求和的最'functional'方法?
- 转换性元素::元素
- 防止在设置高 DPI 时放大 Win32 应用程序的 UI 元素