题目
思路
这道题写的比较多了,主要是想复习一下类的知识,发现好多知识点忘记了;后来想了想其实可以直接比较子字符串大小,不需要转为int 比较
知识点
1. 首先是类的构造函数,c++中类如果你自己写了构造函数,必须要写一个无参的构造函数,否则编译错误;如果自己不写,系统默认帮你构造;而Java却不需要一定要有无参构造函数,我想可能是因为每次都需要new 一下吧
还有,c++类后的大括号要写分号;Java不需要
2. 将一个string作为一个stringstream对象,头文件是< sstream >
string s;
stringstream ss;
ss << s;
代码
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Time {
public:
int hour;
int min;
int sec;
Time(){ hour = 0; min = 0; sec = 0;}
Time(string s){
hour = stoi(s.substr(0,2));
min = stoi(s.substr(3,2));
sec = stoi(s.substr(6,2));
}
};
//全局变量,开门id,和关门id,以及开门的时间,关门的时间
string startId, endId;
Time startTime,endTime;
//和开关门时间进行比较比较
void cmp(string& id,string& startTimeE, string& endTimeE){
Time time1(startTimeE), time2(endTimeE);
if(time1.hour < startTime.hour) {startTime = time1; startId = id;}
if(time1.hour == startTime.hour && time1.min < startTime.min) {startTime = time1; startId = id;}
if(time1.hour == startTime.hour && time1.min == startTime.min && time1.sec <startTime.sec) {startTime = time1; startId = id;}
if(time2.hour > endTime.hour) {endTime = time2; endId = id;}
if(time2.hour == endTime.hour && time2.min > endTime.min) {endTime = time2; endId = id;}
if(time2.hour == endTime.hour && time2.min == endTime.min && time2.sec > endTime.sec) {endTime = time2; endId = id;}
}
int main(){
int cnt = 0;
cin >> cnt;
string c;
getline(cin,c);
for(int i=0; i<cnt; ++i){
string s;
getline(cin,s);//读取一行,getline会读取回车
stringstream ss;
ss << s;
string id,startTimeE,endTimeE;
ss >> id >> startTimeE >> endTimeE;
if(i == 0){
startId = id;
endId = id;
//临时对象startTime1和endTime2
Time startTime1(startTimeE), endTime2(endTimeE);
startTime = startTime1;
endTime = endTime2;
}
else
cmp(id,startTimeE,endTimeE);
}
cout << startId << " " << endId;
return 0;
}