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?
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 <>().
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
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.
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.
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<>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With