
-----------------------------------
HazySmoke)345
Tue Aug 07, 2007 7:41 pm

How to sort in descending order?
-----------------------------------
By default, sort() sorts everthing in ascending order. That's not what I want. First, I tried this:
#include 
#include 
using namespace std;

int comp(int a, int b){
	return b-a;
}

int main(){
	int a[] = {3,6,1,7,1,7,4,2,5,2}, i;
	sort(a, a+10, comp);
	for (i = 0; i < 10; ++i) printf ("%d ", a[i]);
return 0;}

The output turned out to be: 2 5 2 4 7 1 7 1 6 3 - not very appealing.
Then I tried this:

#include 
#include 
using namespace std;

int main(){
	int a[] = {3,6,1,7,1,7,4,2,5,2}, i;
	sort(a, a+10, operator>);
	for (i = 0; i < 10; ++i) printf ("%d ", a[i]);
return 0;}

The compiler gaved me an error...
testing.cpp:7: error: no matching function for call to `sort(int[10], int*, )'

Apparantly it doesn't recognize what 'operator>' is.

What am I doing wrong?

-----------------------------------
PaulButler
Tue Aug 07, 2007 8:39 pm

RE:How to sort in descending order?
-----------------------------------

int comp(int a, int b){
   return b-a;
}


Shouldn't this be:


int comp(int a, int b){
   return b < a;
}


(or b > a?)

-----------------------------------
HazySmoke)345
Tue Aug 07, 2007 9:16 pm

Re: How to sort in descending order?
-----------------------------------
Thanks, you're absolutely right. I guess the compare function works differently in C++ than in C. 8 bits.

I still have no clue why wouldn't operator> work, though. Doesn't C++ treat it like any other functions?

-----------------------------------
OneOffDriveByPoster
Thu Aug 09, 2007 9:20 am

Re: How to sort in descending order?
-----------------------------------
You can try std::greater in .
I still have no clue why wouldn't operator> work, though. Doesn't C++ treat it like any other functions?Yes, but you aren't dealing with operator> when you do ( 0 > 0 ).  You cannot do operator>(0, 0).

-----------------------------------
PaulButler
Fri Aug 10, 2007 7:46 am

RE:How to sort in descending order?
-----------------------------------
Is there not a way to make an infix operator into a function? In OCaml you just wrap it in brackets (eg., 5 + 3 is the same as (+) 5 3). Maybe C++ has something similar?

-----------------------------------
wtd
Fri Aug 10, 2007 11:06 am

RE:How to sort in descending order?
-----------------------------------
O'Caml also lacks operator overloading, which adds some complexity to the issue.

The way one does this in C++ is to create a function object.

template 
struct gt
{
    bool operator()(T a, T b) 
    {
        return a > b;
    }
};
