简体   繁体   English

C++ 按日期排序链表

[英]C++ Sorting linked list by date

I want to sort my linked list by date:我想按日期对我的链表进行排序:

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

It's working now, but just for a year and I have a few more parameters to sort by.它现在正在工作,但仅仅一年,我还有一些参数需要排序。 I want to sort from oldest to newest, I read all data from file.我想从最旧到最新排序,我从文件中读取所有数据。 How can I do it?我该怎么做?

If you are using C++11 (or later) an easy way is to use std::tie from <tuple> .如果您使用 C++11(或更高版本),一个简单的方法是使用<tuple> std::tie

Example use in your code (just guessing here):在您的代码中使用示例(这里只是猜测):

if (std::tie(curr->year, curr->month, curr->day)
  > std::tie(next->year, next->month, next->day)) {
...
}

In your function you just compare the year, if there are data with same years, your function can't sort them.在你的函数中你只是比较年份,如果有相同年份的数据,你的函数不能对它们进行排序。

You can convert DMY time to time_t , like:您可以将 DMY 时间转换为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 refers to the seconds of time in parameters to 1970. time_t是指参数中的时间秒数到 1970。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM