Reputation: 26501
Quite frequently I need to extract the N (> 1) highest elements from an unsorted STL container. The naive way to do this is using <queue>
.
Is there a quicker, less boilerplate way?
Upvotes: 1
Views: 133
Reputation: 476980
To get the n
smallest elements, use 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
Make sure to #include <algorithm>
. An optional predicate may be supplied for customizing the sort order (e.g. std::greater<int>
).
Upvotes: 4
Reputation: 96241
std::partial_sort
if you need them in order, otherwise std::nth_element
, using greater
as your predicate in either case.
I can't tell if by extract you mean you want to remove, but if you do then another option is heapifying your container with make_heap
and then yanking the N
elements out of it.
Upvotes: 3