Sorting a vector in descending order
Should I use
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
or
std::sort(numbers.rbegin(), numbers.rend()); // note: reverse iterators
to sort a vector in descending order? Are there any benefits or drawbacks with one approach or the other?
Actually, the first one is a bad idea. Use either the second one, or this:
struct greater
{
template<class T>
bool operator()(T const &a, T const &b) const { return a > b; }
};
std::sort(numbers.begin(), numbers.end(), greater());
That way your code won't silently break when someone decides numbers
should hold long
or long long
instead of int
.
With c++14 you can do this:
std::sort(numbers.begin(), numbers.end(), std::greater<>());
Use the first:
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
It's explicit of what's going on - less chance of misreading rbegin
as begin
, even with a comment. It's clear and readable which is exactly what you want.
Also, the second one may be less efficient than the first given the nature of reverse iterators, although you would have to profile it to be sure.