Sorting a vector in descending order

fredoverflow picture fredoverflow · Jan 26, 2012 · Viewed 233.9k times · Source

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?

Answer

user541686 picture user541686 · Apr 28, 2013

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.