继我之前的问题之后,我正在寻找一种方法来按类别组织以下结构,就像现在一样,但在组之间进行排序。
例如, GroupMeats
大于 group Drinks
,所以Meats
group 应该在 上面Drinks
,依此类推。
到目前为止,我了解使用的部分qsort()
,但不确定分组部分。这是我正在寻找的输出(我绝对愿意接受更好的方法)
Meats - 43.00
Meats,Chicken - 27.00
Meats,Beef - 9.00
Meats,Pork - 4.00
Meats,Turkey - 3.00
Drinks - 33.00
Drinks,Coffee - 20.00
Drinks,Pepsi - 10.00
Drinks,Tea - 3.00
Fruits - 25.00
Fruits,Grapes - 13.00
Fruits,Melon - 10.00
Fruits,Apple - 2.00
工作代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct st_ex {
char product[96];
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;
int p;
char *iaa = ia->product, *ibb = ib->product;
while (1) {
int c = *iaa;
int d = *ibb;
if(c == ',') c = 0;
if(d == ',') d = 0;
if(c != d || !c || !d) {
p = c - d; break;
}
++iaa;
++ibb;
}
if (p) return p;
return ia->price < ib->price;
}
int main() {
struct st_ex structs[] = {
{"Fruits", 25},
{"Meats,Beef", 9},
{"Fruits,Apple", 2},
{"Meats,Chicken", 27},
{"Fruits,Grapes", 13},
{"Meats", 43},
{"Fruits,Melon", 10},
{"Meats,Pork", 4},
{"Meats,Turkey", 3},
{"Drinks,Tea", 3},
{"Drinks,Coffee", 20},
{"Drinks,Pepsi", 10},
{"Drinks", 33},
};
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("%30s - %.2f\n", structs[i].product, structs[i].price);
return 0;
}