使用结构体,存放年月日,自定义cmp排序
细数遇到的坑()
- 1960-1999排在2000-2059前,在cmp内需要添加特判
- 每个月的天数
- 闰年二月多一天
- 年、日、月数字相同,要去重
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
struct date
{
int x, y, z;
}d[3];//年月日
int days[13] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//月份日期
bool cmp(date d1, date d2)//自定义排序
{
if((d1.x >= 60 && d2.x <=59) || (d1.x <= 59 && d2.x >= 60))//一个世纪的从小到大,不同世纪的从大到小
return d1.x > d2.x;
else if(d1.x != d2.x)
return d1.x < d2.x;
if(d1.y != d2.y)
return d1.y < d2.y;
return d1.z <d2.z;
}
string s;
int to_num(int p1)//字符串变数字
{
int num = 0;
for(int i = 0; i <= 1; i++)
num = num*10 + s[i+p1] - '0';
return num;
}
int main()
{
cin>>s;
int a = to_num(0), b = to_num(3), c = to_num(6);
int t = 1;
d[0] = {a, b, c};
//去重
if(c != a)
{
d[1] = {c, b, a};
t++;
}
if(a != b)
{
d[2] = {c, a ,b};
t++;
}
sort(d, d+t, cmp);
for(int i = 0; i < 3; i++)
{
int year = 0;
int flag = 0;
if(d[i].x >= 60)
year = 1900 + d[i].x;
else
year = 2000 + d[i].x;
if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))//闰年特判
flag = 1;
if(flag == 1)
days[2] = 29;
else
days[2] = 28;
if(d[i].y >= 1 && d[i].y <= 12 && d[i].z >= 1 && d[i].z <=days[d[i].y])
{
cout<<year<<'-';
if(d[i].y < 10)
cout<<'0';
cout<<d[i].y<<'-';
if(d[i].z < 10)
cout<<'0';
cout<<d[i].z<<endl;
}
}
return 0;
}