【问题标题】:How do you sort an array based on more than one field in C?如何根据 C 中的多个字段对数组进行排序?
【发布时间】:2013-10-16 09:40:08
【问题描述】:

我有一系列事件,我想根据它们的年份对它们进行排序,然后按年排序,然后按天排序,然后按小时排序。

typedef struct {
    struct tm start;
    struct tm end;
} event;
...
event events[100];

我只需要担心使用start 日期进行排序。我已经为此苦苦挣扎了好几个小时......

【问题讨论】:

  • 从阅读标准库函数qsort开始。
  • 我以前看过它,只是不知道如何将函数用作它所要求的参数。我现在明白了

标签: c sorting date


【解决方案1】:

与您对多个键进行任何排序的方式相同:一次一个,按照您想要的优先级顺序。

qsort() 回调可能如下所示:

static int event_compare(const void *a, const void *b)
{
  const event *ae = a, *be = b;

  if(ae->start.tm_year < be->start.tm_year)
    return -1;
  else if(ae->start.tm_year > be->start.tm_year)
    return 1;
  /* Years are equal, try to solve that by checking month. */
  if(ae->start.tm_month < be->start.tm_month)
    return -1;
  else if(ae->start.tm_month > be->start.tm_month)
    return 1;
  /* Months are equal, go on with day, and so on. */
}

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 2019-05-21
    • 2021-11-04
    • 2015-06-08
    相关资源
    最近更新 更多