我想以一種particuar的方式排序一個結構。正如你可以在下面的結構中看到的,字段按product
名稱排序。自定義qsort比較函數與結構中的多個字段C
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
謝謝你們,使得現在很多更有意義。 – user1024718