Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use std::sort to find top N items in a std::vector

Tags:

c++

sorting

stl

I need to sort the elements in a std::vector, but I'm only interested in the top N items being sorted, not the entire list:

E.g. in a list of 10 elements, only first 3 have to be sorted. Don't care about the rest...

1,2,3,6,7,4,9,8,5

Can this be done using std::sort?

Edit

I simply needed to find the top N items in a vector. std::partial_sort_copy was exactely what I needed.

like image 695
Radu094 Avatar asked Dec 08 '10 19:12

Radu094


2 Answers

Try std::partial_sort instead of std::sort. :)

like image 120
Karl Knechtel Avatar answered Oct 16 '22 07:10

Karl Knechtel


This is what std::partial_sort is for.

like image 8
aschepler Avatar answered Oct 16 '22 07:10

aschepler