gpt4 book ai didi

c - 有没有办法编写更好的代码来对 C 中的结构进行排序?

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

我想将最便宜的商品排在最前面。 c 代码工作正常,我只是想知道是否有更好的方法在 c 中对结构进行排序?

typedef struct
{
float price;
char product[50];
char brand[50];
}clothes;

void sort(clothes*pt, int count)
{
int a, b;
float price;
char product[50];
char brand[50];
for(a = 0; a < count - 1; a++){
for(b = a + 1; b < count; b++){
if((pt+a)->price > (pt+b)->price){
price = ((pt+b)->price);
strcpy(product,(( pt+b)->product));
strcpy(brand,((pt+b)->brand));
((pt+b)->price) = ((pt+a)->price);
strcpy(((pt+b)->product),((pt+a)->product));
strcpy(((pt+b)->brand),((pt+a)->brand));
((pt+a)->price) = price;
strcpy(((pt+a)->product),product);
strcpy(((pt+a)->brand),brand);
}
}
}
}

最佳答案

您可以,而且您可能应该使用标准排序函数 qsort(3) .你需要给它一个比较功能。

static int compare_clothes_by_price (const void*p1, const void*p2) 
{
const clothes* c1 = (const clothes*)p1;
const clothes* c2 = (const clothes*)p2;
if (c1->price == c2->price) return 0;
else if (c1->price < c2-price) return -1;
else if (c1->price > c2-price) return 1;
// this is reached only if a price is NAN
abort();
}

然后你打电话

 qsort(pt, count, sizeof(clothes), compare_clothes_by_price);

关于c - 有没有办法编写更好的代码来对 C 中的结构进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27091829/

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