0

我有一个需要按升序排序的结构:

typedef struct CallLogSearchDataStruct
{
    char * date;
    char * time;
    char * bParty;
    char * aParty;
    float duration;
    char * cleardownCause;
    struct CallLogSearchOutboundStruct * outboundLegs;
    int maxDataCol;
} callLogSearchDataStruct;

我需要根据日期和时间按升序对结构进行排序。日期和时间采用以下格式

日期:16/05/2011时间:01:20:03

我需要按升序对上述两个字段进行排序,我一直在研究 qsort 但我想不出一种方法来做到这一点。我通过以下方式调用该函数。

qsort(callLogSearchData, dataRow, sizeof(callLogSearchDataStruct), sortCompare);

我的功能如下

int sortCompare(const void * a, const void * b)
{
    const callLogSearchDataStruct *u1 = a;
    const callLogSearchDataStruct *u2 = b;

    if (u1->date < u2->date)
    {
        return -1;
    }
    else if (u1->date > u2->date)
    {
        return 1;
    }
    else
    {
        return 0;
    }

}

当我执行上面的代码时,它似乎没有对其进行排序,而是搞砸了结构的布局,即当我将结构的内容导出到文件时,所有内容都以错误的列顺序出现,而它是很好,除非比较未完成,排序顺序错误。

4

2 回答 2

5

You are comparing pointers, which is certainly not what you are looking for. Here's one approach to compare the structs:

  • Parse the strings and extract individual components like year, month day etc
  • Fill a struct tm with required details and call mktime on it
  • At this point you've got 2 time_t values which you can compare using difftime

This sounds like a lot of work, and it is! If you're willing to go a little non-portable you can try the wonderful strptime which converts strings to struct tms.

于 2013-09-25T09:09:56.370 回答
0

似乎您正在比较字符指针并基于此做出决定。但是您必须比较日期和时间值才能进行排序。因为它们都是字符串,你应该解析字符串,在不同的变量中获取年、月、日、小时、秒。现在你可以使用

mktime()

它会以 time_t 格式返回给您。现在您可以轻松地比较它们并进行相应的排序。

于 2013-09-25T09:16:05.817 回答