tags:

views:

384

answers:

7

I have

sort(arr, arr+n, pred);

How do I sort in reverse order?

+1  A: 

Negate the return value of pred.

Troubadour
I think you need more than this. Pred needs to be a strict weak ordering, e.g., like < not <=. If you negate a strict weak ordering you don't get another strict weak ordering: negating < turns into >= not >.
David Norman
David's right, you need to reverse the operands, not negate the return value.
Steve Jessop
@David: Fair point.
Troubadour
+4  A: 

You could use greater from the standard library which calls operator> automatically for the type you want to sort.

#include <funcitonal>
.....
sort(arr, arr+n, greater<Type>()); // Type could be double for example
AraK
+1  A: 

As alrady said, you should provde a reversed predicate. If you can't for some reasons (like pure laziness), you can always first sort then reverse :

sort(arr, arr+n, pred);
reverse( arr, arr+n );

That would be more work for the computer but it's clear and does the job. If you need speed performance for this sort, use the reversed predicate solution.

Klaim
+4  A: 

There also seems to be a possibility to use reverse iterators ... except using the reversed predicate might be easier, except perhaps when the type doesn't implement operator> :)

#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    int arr[4] = { 3, 2, 5, 4 };
    std::sort(std::reverse_iterator<int*>(arr + 4), std::reverse_iterator<int*>(arr));
}
UncleBens
this is what I was looking for, thanks
Neil G
+3  A: 

If you're given pred (i.e. you can't get inside it to reverse the order), something like:

std::sort(arr, arr+n, boost:bind<bool>(pred, _2, _1));
Steve Jessop
A: 

Quite Easy i seems

std::sort(myVec.rbegin(),myVec.rend());


int main() 
{
    typedef std::vector<int> vecType;
    vecType myVec;
    for(int a=0;a<20;a++)
    {
     myVec.push_back((rand()%100));
    }
    std::copy(myVec.begin(), myVec.end(), std::ostream_iterator<int>(std::cout, "\n"));
    cout<<"\n---------------------------------------------------\n";
    std::sort(myVec.rbegin(),myVec.rend());
    std::copy(myVec.begin(), myVec.end(), std::ostream_iterator<int>(std::cout, "\n"));
    return 0; 
}
sat
A: 
sort(arr, arr+n, std::not1(pred));

See: http://www.cplusplus.com/reference/std/functional/not1/

AshleysBrain
Wrong: pred(a,a) will return false, as it should, but `not1(pred(a,a))` incorrectly returns true. This may cause `sort()` to hang.
MSalters