我想按日期对链接列表进行排序:
void sortuj(List *head)
{
List curr = *head;
List next;
int temp;
while (curr && curr->next)
{
next = curr->next;
while (next)
{
if (curr->year > next->year)
{
std::swap(next->day, curr->day);
std::swap(next->month, curr->month);
std::swap(next->year, curr->year);
std::swap(next->hour, curr->hour);
std::swap(next->minute, curr->minute);
std::swap(next->length, curr->length);
std::swap(next->group, curr->group);
std::swap(next->description, curr->description);
}
next = next->next;
}
curr = curr->next;
}
}
它现在正在工作,但仅仅一年,我还有一些参数要排序。我想从最旧到最新排序,我从文件中读取所有数据。我该怎么办?
答案 0 :(得分:0)
如果您使用的是C ++ 11(或更高版本),一种简单的方法是使用std::tie
中的<tuple>
。
在您的代码中使用示例(只是在这里猜测):
if (std::tie(curr->year, curr->month, curr->day)
> std::tie(next->year, next->month, next->day)) {
...
}
答案 1 :(得分:0)
在您的功能中,您只需比较年份,如果有相同年份的数据,您的功能无法对它们进行排序。
您可以将D-M-Y时间转换为time_t
,例如:
#include <time.h>
...
time_t convertTime(List& l)
{
/*struct*/ tm _tm;
_tm.tm_year = l.year;
_tm.tm_mon = l.month;
_tm.tm_mday = l.day;
_tm.tm_hour = l.hour;
_tm.tm_min = l.minute;
_tm.tm_sec = l.second;
_tm.tm_isdst = 0;
return mktime(&_tm);
}
time_t
指的是1970年参数的秒数。