从容器中提取N个最高元素

C++: Extract N highest elements from container

本文关键字:高元素 元素 提取      更新时间:2023-10-16

我经常需要从未排序的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元素。