比較日期有時候讓人頭疼,需要考慮很多情況,這裏通過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;
}