c++ sort cmp规则 题：日期排序

题目 1227: 日期排序

``````15/12/1999
10/21/2003
10/22/2003
02/12/2004
11/30/2005
12/31/2005
``````

``````15/12/1999
10/21/2003
10/22/2003
02/12/2004
11/30/2005
12/31/2005
``````

题解：

``````
int i,j;
for(i=0;i<len-1;i++)
for(j=0;j<len-1-i;j++){
if(d[j].year>d[j+1].year)
swap(d[j],d[j+1]);
else if(d[j].year==d[j+1].year){
if(d[j].month>d[j+1].month)
swap(d[j],d[j+1]);
else if(d[j].month==d[j+1].month)
if(d[j].day>d[j+1].day)
swap(d[j],d[j+1]);
}
}

/*
void swap(date d1,date d2){
date d3;
d3=d2;
d2=d1;
d1=d3;
}

*/
``````

``````02/12/2004
``````

代码实现

``````#include <iostream>
#include <algorithm>
#include<iomanip>
using namespace std;

typedef struct date{
int month;
int day;
int year;
} date;

date d[1001];
int len;

bool cmp(date d1,date d2){
if(d1.year!=d2.year)
return d1.year < d2.year;
else if(d1.month!=d2.month)
return d1.month < d2.month;
else if(d1.day!=d2.day)
return d1.day < d2.day;
}

int main(){

date td;
//接受输入
int len=0,i;
char c;
while(cin>>d[len].month>>c>>d[len].day>>c>>d[len].year)
len++;

sort(d,d+len,cmp);
for(i=0;i<len;i++)
cout<<setw(2)<<setfill('0')<<d[i].month<<'/'<<setw(2)<<setfill('0')<<d[i].day<<'/'<<d[i].year<<endl;
}

``````