我有一个结构:
struct pkt_
{
double x;
double y;
double alfa;
double r_kw;
};
typedef struct pkt_ pkt;
这些结构的表格:
pkt *tab_pkt;
tab_pkt = malloc(ilosc_pkt * sizeof(pkt));
我想做的是按tab_pkt.alfa
和tab_pkt.r
对tab_pkt
进行排序:
qsort(tab_pkt, ilosc_pkt, sizeof(pkt), porownaj);
其中porownaj是比较函数,但是怎么写呢?这是我的“草图”:
int porownaj(const void *pkt_a, const void *pkt_b)
{
if (pkt_a.alfa > pkt_b.alfa && pkt_a.r_kw > pkt_b.r_kw) return 1;
if (pkt_a.alfa == pkt_b.alfa && pkt_a.r_kw == pkt_b.r_kw) return 0;
if (pkt_a.alfa < pkt_b.alfa && pkt_a.r_kw < pkt_b.r_kw) return -1;
}
最佳答案
像这样的东西应该可以工作:
int porownaj(const void *p_a, const void *p_b)
{
/* Need to store arguments in appropriate type before using */
const pkt *pkt_a = p_a;
const pkt *pkt_b = p_b;
/* Return 1 or -1 if alfa members are not equal */
if (pkt_a->alfa > pkt_b->alfa) return 1;
if (pkt_a->alfa < pkt_b->alfa) return -1;
/* If alfa members are equal return 1 or -1 if r_kw members not equal */
if (pkt_a->r_kw > pkt_b->r_kw) return 1;
if (pkt_a->r_kw < pkt_b->r_kw) return -1;
/* Return 0 if both members are equal in both structures */
return 0;
}
远离愚蠢的技巧,例如:
return pkt_a->r_kw - pkt_b->r_kw;
它返回非规范化的值,读起来很困惑,对 float 不能正常工作,有时有棘手的极端情况,即使对整数值也不能正常工作。
关于c - 如何从 stdlib 为 qsort 编写比较函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/327893/