Reputation: 33202
I have
sort(arr, arr+n, pred);
How do I sort in reverse order?
Upvotes: 0
Views: 2295
Reputation: 22591
sort(arr, arr+n, std::not1(pred));
See: http://www.cplusplus.com/reference/std/functional/not1/
Upvotes: 0
Reputation: 6506
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;
}
Upvotes: 0
Reputation: 279255
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));
Upvotes: 4
Reputation: 41331
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));
}
Upvotes: 9
Reputation: 69682
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.
Upvotes: 1
Reputation: 96869
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
Upvotes: 3