gpt4 book ai didi

C 中结构内具有多个字段的自定义 qsort 比较器函数

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:57 24 4
gpt4 key购买 nike

我正在尝试以特定方式对结构进行排序。正如您在以下结构中看到的,字段按 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

我想知道如何保留按产品 名称排序,但同时按价格“子排序”每个产品。

这是我目前所拥有的:

#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

最佳答案

最简单的方法是修改您的struct_cmp_by_product。不要执行 strcmp,而是比较产品名称(取决于您的产品名称的长度,您可能希望在 product< 的子字符串上使用 strcmp/成员)。

不过,我更愿意通过保留两个成员来在 st_ex 类型中对这种区别进行编码,这两个成员组合在一起时会给出实际的产品名称。

 struct st_ex {
char product[ 4 ]; // product group
char subgroup[ 12 ]; // sub group
float price;
}

int struct_cmp_by_product(const void *a, const void *b) {
struct st_ex const *ia = a; // do not cast away const-ness!
struct st_ex const *ib = b;
int x = strcmp(ia->product, ib->product);
if (!x) {
return ia->price > ib->price;
}
return x;
}

关于C 中结构内具有多个字段的自定义 qsort 比较器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com