0

ALL,

std::sort() will sort in ascending order. Is there an easy, convenient and fast way of doing a descending sort?

Thank you.

Igor
  • 5,620
  • 11
  • 51
  • 103
  • 1
    [`std::greater<>`](http://en.cppreference.com/w/cpp/utility/functional/greater) – chris Mar 21 '13 at 22:32
  • http://stackoverflow.com/questions/9025084/sorting-a-vector-in-descending-order shows you 2 ways – user93353 Mar 21 '13 at 22:34
  • @user93353, thank you. As I don't use primitives, but a custom made objects I will probably use the second way. (I wish I could accept you answer.) – Igor Mar 21 '13 at 23:35

2 Answers2

7

If you're sorting ints, say, in the range [begin, end):

std::sort(begin, end, std::greater<int>());

std::greater is a binary function object that applies > to its operands. You could alternatively provide a lambda expression:

std::sort(begin, end, [](int a, int b) { return a > b; });
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • No, I am sorting a custom made object, not a primitive. – Igor Mar 21 '13 at 23:25
  • @Igor Then you'll need to pass a function object (perhaps a lambda as above) that takes two `const T&` arguments (where `T` is your type) and returns `true` if the first is less than the second. – Joseph Mansfield Mar 21 '13 at 23:28
  • This is what I do: struct Sorter { bool operator()(const CObj &obj1, const CObj &obj2) { return obj1.m_num < obj2.m_num; } } Then somewhere in the code: std::sort( obj1.begin(), obj2.end(), sorter ); I can't use lambda as this will be ported to Mac and it will be compiled under 10.6 which does not support C++11. Any way to modify this? Or I am better off with reverse iterators? – Igor Mar 21 '13 at 23:46
  • @Igor: If it makes sense for your objects to be compared with `operator<` you can just implement that operator. (Same with `operator>`, `operator==`, `operator>=` etc.; implement them in terms of each other.) Then `std::greater` will just do the right thing. – GManNickG Mar 21 '13 at 23:58
2

Write a function to compare:

bool comp(int a, int b)
{
    return a > b;
}

then to sort, say, a vector vec, call sort(vec.begin(), vec.end(), comp)

tianz
  • 2,155
  • 2
  • 19
  • 28