C ++ - 如何对链表中的数据进行排序并显示它?

时间:2018-05-07 02:34:17

标签: c++ class sorting linked-list

我目前正在开发一个有链表的程序。我的程序需要有一个函数,可以根据几个月对所有数据进行排序,然后显示所有数据,但我找不到一个很好的例子供我参考,因为在我的情况下我需要搜索{{ 1}}以这种方式输入 dd / mm / yyyy 这意味着我需要使用string expireDate;来获取其子字符串,以便我获得月份然后将子字符串转换为使用std::string str2 = temp->expireDate.substr(3,2);的整数。请看一下我的代码,它已经过排序,但是当我运行它时它没有显示任何内容,我认为肯定会有一个小错误。我已经弄清楚了我的错误,实际上这只是一个愚蠢的错误。这段代码没有错误。

int month;

1 个答案:

答案 0 :(得分:0)

您是否可以使用所有C ++,或者您是否真的只允许将C与std :: string和std :: cout一起使用?

如果你可以使用C ++,我会怎么做(仍然使用链表,因为你在你的问题中指定了 - 如果你不需要使用std :: vector和std :: sort会更有效率链表):

#include <iostream>
#include <sstream>
#include <iterator>
#include <locale>
#include <vector>
#include <list>

// define a facet that adds slash to the list of delimiters
class slash_is_space : public std::ctype<char> {
public:
    mask const *get_table() { 
        static std::vector<std::ctype<char>::mask> 
            table(classic_table(), classic_table()+table_size);
        table['/'] = (mask)space;
        return &table[0];
    }
    slash_is_space(size_t refs=0) : std::ctype<char>(get_table(), false, refs) { }
};

// define a class (with public members) that adds splits the date using the new facet
struct extract_date
{
    int day, month, year;
    extract_date(std::string date) {
        std::stringstream ss(date);
        ss.imbue(std::locale(std::locale(), new slash_is_space));
        ss >> day >> month >> year;
    }
};

// your struct containing the date that will be used for sorting
struct carInsurance
{
    std::string carNo;
    std::string expireDate;
    std::string carUsage;
    std::string manufacturingDate;
};

// a function that can print your struct
std::ostream& operator << ( std::ostream& out, const carInsurance& rhs )
{
    out << rhs.carNo      << ", "
        << rhs.expireDate << ", "
        << rhs.carUsage   << ", "
        << rhs.manufacturingDate;
    return out;
}

int main()
{
    // your linked list of data
    std::list<carInsurance> cars{{"a","00/01/0000","a","a"},
                                 {"b","00/03/0000","b","b"},
                                 {"c","00/02/0000","c","c"}};

    // sort the list by expireDate month
    cars.sort([](carInsurance& a, carInsurance& b){
        extract_date a_date(a.expireDate);
        extract_date b_date(b.expireDate);
        return a_date.month < b_date.month;
    });

    // print the sorted list
    std::copy(cars.begin(), cars.end(), std::ostream_iterator<carInsurance>(std::cout, "\n"));

    return 0;
}