我正在尝试以特定的方式对结构进行排序。正如您在以下结构中看到的那样,字段按product
名称排序。
a - $13.00
a.0|100 - $3.00
a.1|100 - $6.00
a.2|100 - $4.00
b - $25.00
b.0|100 - $2.00
b.1|100 - $10.00
b.2|100 - $13.00
我想知道如何按product
名称保留排序,但同时按price
.
这是我到目前为止所拥有的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct st_ex {
char product[16];
float price;
};
int struct_cmp_by_product(const void *a, const void *b) {
struct st_ex *ia = (struct st_ex *)a;
struct st_ex *ib = (struct st_ex *)b;
return strcmp(ia->product, ib->product);
}
int main() {
struct st_ex structs[] = {
{"b", 25},
{"b.0|100", 2},
{"b.1|100", 10},
{"b.2|100", 13},
{"a", 13},
{"a.0|100", 3},
{"a.1|100", 6},
{"a.2|100", 4},
};
size_t structs_len = sizeof(structs) / sizeof(struct st_ex);
qsort(structs, structs_len, sizeof(struct st_ex), struct_cmp_by_product);
size_t i;
for(i=0; i<structs_len; i++)
printf("%8s - $%.2f\n", structs[i].product, structs[i].price);
return 0;
}
更新:按价格排序,但按名称分组。例如,b:25
>a:13
b - $25.00
b.2|100 - $13.00
b.1|100 - $10.00
b.0|100 - $2.00
a - $13.00
a.1|100 - $6.00
a.2|100 - $4.00
a.0|100 - $3.00