问题
Let's suppose we have a structure:
struct product
{
char name[30];
float price;
};
I want to sort it using qsort first by price, and if the prices are equal, by name. How I thought of writing the compare function:
int compare(const void *a, const void *b )
{
int comp = a.price - b.price;
if (comp < 0 )
return 1
if (comp > 0 )
return 0;
comp = strcmp(a.name, b.name);
if ( comp < 0 )
return 1;
else
if ( comp > 0 )
return 0;
}
Since I have only used the usual compare function for qsort, I don't know how to go about this. I think that I'm accessing the fields incorrectly, based on the errors given, so could you please point out my mistakes writing the compare function?
回答1:
Your code as written has several syntax errors, and also your comparison function doesn't do quite what you want. Quoting from the manpage for qsort
:
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respec‐ tively less than, equal to, or greater than the second. If two mem‐ bers compare as equal, their order in the sorted array is undefined.
Consider the following code:
#include <stdlib.h>
#include <string.h>
struct product {
char name[30];
float price;
};
int compare(const void *a, const void *b) {
const struct product *x = a; // void* can be assigned to any other pointer type
const struct product *y = b;
int comp = x->price - y->price;
if (comp < 0)
return -1;
if (comp > 0)
return 1;
comp = strcmp(x->name, y->name);
return comp;
}
If you want to reverse the sort order, negate comp
at the appropriate place.
As others have mentioned, this is C code, and is not idiomatic C++.
来源:https://stackoverflow.com/questions/23732011/compare-function-for-qsort-using-two-fields-of-a-structure