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

标签 c struct qsort

我有一个结构

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/

相关文章:

c - 给array seat赋值很慢

c - 访问诸如变量->成员之类的内容时什么时候需要括号?

MATLAB:错误使用 * 内部矩阵维度必须一致

c - 在自身内部定义结构对象的问题

c - qsort段错误

比较、组合和确定字符串的长度?

c - 大型与嵌套状态机

c - 动态访问结构的字段

c - Qsort 数组 |警告 : initialization discards qualifiers from pointer target type

c - Qsorting 二维指针数组