【问题标题】:sorting an array of structures by 2 parameters按 2 个参数对结构数组进行排序
【发布时间】:2014-11-22 20:04:35
【问题描述】:

我有一个结构

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;
}

但这不起作用...

有什么帮助吗?

【问题讨论】:

  • 如果您甚至不提及record 字段,它怎么可能起作用? (什么是zam?应该是void。)
  • 将 p1 和 p2 类型转换为员工?不确定那里是否有某种继承或 zam 与员工的关系
  • zam 是员工的意思,我把它翻译成英文忘了这个..
  • 你为什么要像 qSort(employee, ...

标签: c struct qsort


【解决方案1】:

通常的方式是这样的:

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;
}

改为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 2015-03-16
    • 2011-02-23
    • 1970-01-01
    相关资源
    最近更新 更多