描述:给定一组记录n(n<100)小明各个时期的考试成绩,格式为日期+成绩,中间以空格隔开,记录之间分行输入,例如
2009/6/3 80
2009/1/1 56
…
其中日期输入要求年份1996-2100 月份1-12 日期1-31
现要求以分数为 关键字从大到小对其进行排序,若分数相同则按日期从小到大排序
输入样例
4
2017/1/1 95
2017/6/10 85
2017/3/2 95
2017/1/1 65
输出样例
2017/1/1 95
2017/3/2 95
2017/6/10 85
2017/1/1 65
#include "iostream"
#include "cstring"
#include "algorithm"
#define MAX 100
#define isLeap(x) x%4==0&&x%100!=0||x%400==0 //判断是否是闰年
using namespace std;
int Day[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
typedef struct{
char date[100];
int grade;
}Record;
bool cmp(Record x,Record y){ //定义结构体的比较方法
if(x.grade!=y.grade)
return x.grade > y.grade;
return x.date < y.date;
}
bool isValid(char *str){ //日期是否正确
int y,m,d;
int Feb; //二月天数
bool valid = true;
sscanf(str,"%d/%d/%d",&y,&m,&d); //按照格式读取str的值
if(y<1996||y>2100)
valid=false;
if(m<1||m>12)
valid=false;
if(isLeap(y)&&m==2) //闰年二月
Feb=Day[m]+1;
else
Feb=Day[m];
if(d<1||d>Day[m])
valid=false;
return valid;
}
int main(){
Record res[MAX];
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>res[i].date>>res[i].grade;
//根据自定义排序规则排序
sort(res,res+n,cmp);
for(int i=0;i<n;i++){
if(isValid(res[i].date))
cout<<res[i].date<<" "<<res[i].grade<<endl;
}
return 0;
}
结构体排序那个没想到,按照格式读取之前也不了解