inconsistency of c/c++

T

thomas

Hi,
I have found one interesting thing.

the qsort() for c:
--------------c----
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b ); -----(1)
}
qsort (values, 6, sizeof(int), compare);
-------------c++----
bool cmp(const int &a, const int &b){
return a<b; -----(2)
}
sort(values, values+6, cmp);
--------------------

We find that both sort the "values" array in ascending order, the first
(1) uses a converse comparison results with (2).
It says that if "compare" returns positive, we should put "a"
backwords for qsort; but if "cmp" returns true(like positive), we
should put "a" in front for sort.
 
V

Victor Bazarov

thomas said:
Hi,
I have found one interesting thing.

the qsort() for c:
--------------c----
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b ); -----(1)
}
qsort (values, 6, sizeof(int), compare);
-------------c++----
bool cmp(const int &a, const int &b){
return a<b; -----(2)
}
sort(values, values+6, cmp);
--------------------

We find that both sort the "values" array in ascending order, the first
(1) uses a converse comparison results with (2).
It says that if "compare" returns positive, we should put "a"
backwords for qsort; but if "cmp" returns true(like positive), we
should put "a" in front for sort.

It's not an inconsistency, really. The 'qsort' uses a special
comparison functor, which is "greater", "equal", and "less" combined,
whereas 'std::sort' uses only 'less'.

Change the word "positive" in your statement which starts with "It
says.." to "negative", and there is no "but". If "compare" returns
negative qsort will put 'a' before 'b', so will 'sort' if "cmp" returns
"true".

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top