开发者

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

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 s开发者_JAVA百科orted. 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.


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


This is what std::partial_sort is for.


If you require ordering then partial_sort will do it, otherwise if you only need to partition the range nth_element will do it faster.


Just tell the sort routine where you want to stop sorting:

std::vector<int> values;
for (int i = 0; i < 10; ++i)
    values.push_back(rand() % 10);

std::cout << "UNSORTED" << endl;
std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;

std::cout << "SORTED (Partially)" << std::endl;
std::sort(values.begin(), values.begin() + 3);
std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜