Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 826
fredoverflow Avatar asked Jan 26 '12 20:01

fredoverflow


People also ask

How do you sort descending in vector?

Sorting a vector in descending order in C++ To get a stable sort std::stable_sort is used. It is exactly like sort() but maintain the relative order of equal elements. Quicksort(), mergesort() can also be used, as per requirement. Sorting a vector in descending order can be done by using std::greater <>().

How do you sort in descending order?

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you sort a vector in descending order in R?

sort() function in R is used to sort a vector. By default, it sorts a vector in increasing order. To sort in descending order, add a “decreasing” parameter to the sort function.

How do you know if a vector is sorted in descending order?

To check for a sorted array in descending order, you can pass the comparison function std::greater<int>() that represents an object class for greater-than inequality comparison.


2 Answers

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.

like image 124
user541686 Avatar answered Oct 22 '22 13:10

user541686


With c++14 you can do this:

std::sort(numbers.begin(), numbers.end(), std::greater<>());
like image 117
mrexciting Avatar answered Oct 22 '22 11:10

mrexciting