题目描述
已有一个日期类Date,包括三个protected成员数据year,month,day;
另有一个时间类Time,包括三个protected成员数据hour,minute,second,12小时制;
现需根据输入的日程的日期时间,安排前后顺序,为此以Date类和Time类为基类,建立一个日程类Schedule,包括以下新增成员:
int ID;//日程的ID
定义友元函数bool before(const Schedule & s1,const Schedule & s2);//判断日程s1时间是否早于日程s2。
编写主函数,根据输入的各项日程信息,建立日程对象,找出需要最早安排的日程(日期和时间相等时,输出较早建立的日程),并输出该日程对象的信息。
输入
测试输入包含若干日程,每个日程占一行(日程ID、日程日期、日程时间)。
当读入0时输入结束,相应的结果不要输出。
输出
时间最靠前的日程
样例
输入:
1 2019 6 27 8 0 1
2 2019 6 28 8 0 1
3 2020 1 1 8 0 0
0
输出:The urgent schedule is No.1: 2019/06/27 08:00:01
#include<iostream>
#include<cstring>
#include<iomanip>
#include<algorithm>
using namespace std;
class Date {
protected:
int year;
int month;
int day;
public:
Date(int y=0,int m=0,int d=0):year(y),month(m),day(d){}
void print()
{
cout << year << "/" << fixed << setw(2) << setfill('0')<<month << "/" << fixed << setw(2) << setfill('0')<<day << " ";
}
};
class Time {
protected:
int hour, minute, second;
public:
Time(int h=0,int m=0,int s=0):hour(h),minute(m),second(s){}
void print()
{
cout << fixed << setw(2) << setfill('0') << hour << ":" << fixed << setw(2) << setfill('0') << minute << ":" << fixed << setw(2) << setfill('0') << second;
}
};
class Schedule :public Date, public Time {
int ID;
public:
Schedule(int y=0,int m=0,int d=0,int h=0,int mm=0,int s=0,int i=0):Date(y,m,d),Time(h,mm,s),ID(i){}
void sett(int y = 0, int m = 0, int d = 0, int h = 0, int mm = 0, int s = 0, int i = 0)
{
year = y; month = m; day = d;
hour = h; minute = mm; second = s;
ID = i;
}
void print()
{
cout << "No." << ID << ": ";
Date::print();
Time::print();
}
friend bool before(const Schedule& s1,const Schedule& s2);
};
bool before(const Schedule& s1,const Schedule& s2)
{
int m1 = s1.year * 10000 + s1.month * 100 + s1.day;
int m2 = s2.year * 10000 + s2.month * 100 + s2.day;
int n1 = s1.hour * 10000 + s1.minute * 100 + s1.second;
int n2 = s2.hour * 10000 + s2.minute * 100 + s2.second;
if (m1 <= m2 && n1 <n2)return true;
else return false;
}
int main()
{
int id;
int y, m, d, h, mm, s;
int cnt = 0;
Schedule a[100];
while (1)
{
cin >> id;
if (id == 0)break;
cin >> y >> m >> d >> h >> mm >> s;
a[cnt].sett(y, m, d, h, mm, s,id);
cnt++;
}
sort(a, a + cnt, before);
cout << "The urgent schedule is ";
a[0].print();
return 0;
}
ps:本体使用sort函数可极大简化程序,sort函数在<iomanip>中。