gpt4 book ai didi

c - 按 2 个参数对结构体数组进行排序

转载 作者:行者123 更新时间:2023-11-30 17:25:22 24 4
gpt4 key购买 nike

我有一个结构

struct employee {
int record;
int ID;
....
};

employee * arr = (employee*) malloc(501 * sizeof (employee));

我需要按这两个参数对其进行排序(第一个是 ID,第二个是记录)。我正在使用标准 Qsort

 qsort (employee, records, sizeof(employee), compare);

但我不知道如何编辑基本比较函数,使其正常工作

我也有这样的事情

int comparestruct(const employee *p1, const employee *p2)
{
const struct employee *elem1 = p1;
const struct employee *elem2 = p2;

if ( elem1->ID < elem2->ID)
return -1;
else if (elem1->ID > elem2->ID)
return 1;
else
return 0;
}

但这不起作用...

请问有什么帮助吗?

最佳答案

通常的方式是这样的:

int comparestruct(const void *a_, const void *b_) {
const struct employee *a = a_;
const struct employee *b = b_;
int rv = a->ID - b->ID;
if (rv == 0) rv = a->record - b->record;
return rv;
}

当然,如果减法可能溢出(这取决于您的 ID 和记录编号的范围),这会存在一个微妙的错误。如果这是一个可能的问题,您可能需要:

int comparestruct(const void *a_, const void *b_) {
const struct employee *a = a_;
const struct employee *b = b_;
if (a->ID < b->ID) return -1;
if (a->ID > b->ID) return 1;
if (a->record < b->record) return -1;
if (a->record > b->record) return 1;
return 0;
}

相反

关于c - 按 2 个参数对结构体数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27081900/

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