比较日期有时候让人头疼,需要考虑很多情况,这里通过stringstream的方法实现一组日期的排序。
#include <iostream>
using namespace std;
#include<algorithm>
#include<sstream>
#include<iomanip>
struct Date{ //创建日期结构体
int year, month, day;
};
bool cmp(Date s1,Date s2)
{
string date1, date2;
stringstream stream1;
//把日期输进流里。
stream1 << s1.year << setfill('0') << setw(2) << s1.month << setfill('0') << setw(2) << s1.day;
//流的值赋给date1.
date1 = stream1.str();
stringstream stream2;
stream2 << s2.year << setfill('0') << setw(2) << s2.month << setfill('0') << setw(2) << s2.day;
date2 = stream2.str();
//返回小的值
return (date1<date2);
}
int main()
{
int n;
cin >> n;
Date date[100]; //创建结构体数组
for (int i = 0; i < n; i++)
{
cin >> date[i].year >> date[i].month >> date[i].day;
}
sort(date,date+n,cmp); //调用
cout << endl;
for (int i = 0; i < n; i++)
cout << date[i].year << " " << date[i].month << " " << date[i].day << endl;
}