题目:
按照年月日进行排序,若年相同则按月排序,若月也相同则按日期排序;
解答:
#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
using namespace std;
class Date{
private:
int year;
int month;
int day;
public:
Date(int y=0,int m=0,int d=0):year(y),month(m),day(d){}
friend bool operator<(const Date & a,const Date &b) //重载<运算符 因为SET容器排序需要用到
{
if(a.year==b.year)
{
if(a.month==b.month)
return a.day<b.day;
else
return a.month<b.month;
}
else return a.year<b.year;
}
friend ostream &operator<<(ostream &os,Date d){ //重载>>运算符 因为ostream迭代器 需要调用
os<<d.year<<"/"<<d.month<<"/"<<d.day;
return os;
}
};
int main()
{ int y,m,d,n;
multiset <Date> date;
cin>>n; //multiset 容器 输入时间可重复
cin>>y>>m>>d;
while(n)
{
date.insert(Date(y,m,d));
n--;
if(n!=0) cin>>y>>m>>d;
}
copy(date.begin(),date.end(),ostream_iterator <Date,char>(cout,"\n")); //遍历输出容器
return 0;
}
multiset
是<set>
库中一个非常有用的类型,它可以看成一个序列,插入一个数,删除一个数都能够在O(logn)的时间内完成,而且他能时刻保证序列中的数是有序的,而且序列中可以存在重复的数
当然也可以将Data存在vector中,并用sort和cmp结合来实现该vector的排序 —— 不如multiset简洁。