## sort/qsort compare function [Resolved]

Write here if you have problems with your C++ source code

Moderator: Board moderators

bugzpodder
Experienced poster
Posts: 147
Joined: Fri Jun 13, 2003 10:46 pm

### sort/qsort compare function [Resolved]

to my understanding the sort function in the STL algorithms header and the function that qsort (standard C) takes in should be completely opposite right?
consider
compareTo(int a1,int a2)
in the STL sort, we must return 1 (true) if a1 goes before a2
and in the C qsort, we must return -1 if a1 goes before a2?

can anyone confirm (or deny)?

thanks
Last edited by bugzpodder on Mon Aug 23, 2004 8:14 pm, edited 1 time in total.

Viktoras Jucikas
New poster
Posts: 22
Joined: Sun Oct 20, 2002 6:41 pm
Location: Lithuania
Contact:
Confirmed

From http://www.sgi.com/tech/stl/sort.html:

Sort sorts the elements in [first, last) into ascending order, meaning that if i and j are any two valid iterators in [first, last) such that i precedes j, then *j is not less than *i.

Actually sort uses operator< to compare elements (or given function object if you use version with three parameters - to obtain ascending sequence this function should behave like operator<, i.e. return true if first operand is smaller(equals) than the second one)

From MSDN:
qsort comparing routine
compare( (void *) elem1, (void *) elem2 );
must compare the elements, then return one of the following values:

< 0 elem1 less than elem2
0 elem1 equivalent to elem2
> 0 elem1 greater than elem2

The array is sorted in increasing order, as defined by the comparison function. To sort an array in decreasing order, reverse the sense of