題目來源:http://ac.jobdu.com/problem.php?pid=1013
我的代碼:已ac
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
class Employee{
// string s;
char* s;
int hour1,hour2;
int minute1,minute2;
int second1,second2;
public:
Employee(char* str=0,int h1=0,int s1=0,int m1=0,int h2=0,int s2=0,int m2=0):s(str),hour1(h1),minute1(s1),second1(m1),hour2(h2),minute2(s2),second2(m2){}
void print(){
cout<<s;
}
booloperator> (constEmployee& a){
if(this->hour1>a.hour1)
return true;
else if(this->hour1==a.hour1){
if(this->minute1>a.minute1)
return true;
else if(this->minute1==a.minute1){
if(this->second1>a.second1)
return true;
else if(this->second1<a.second1)
return false;
}
else if(this->minute1<a.minute1)
return false;
}
else if(this->hour1<a.hour1)
return false;
return true;
}
booloperator< (constEmployee& a){
if(this->hour2<a.hour2)
return true;
else if(this->hour2==a.hour2){
if(this->minute2<a.minute2)
return true;
else if(this->minute2==a.minute2){
if(this->second2<a.second2)
return true;
else if(this->second2>a.second2)
return false;
}
else if(this->minute2>a.minute2)
return false;
}
else if(this->hour2>a.hour2)
return false;
return true;
}
};
Employee employee[100];
int main(){
int n;
int m;
// string tstr;
int th1,ts1,tm1;
int th2,ts2,tm2;
scanf("%d",&n);
while(n--){
int i=0;
scanf("%d",&m);
while(i<m){
// char tstr[15];
char* tstr=newchar[15];
scanf("%s %2d:%2d:%2d %2d:%2d:%2d",tstr,&th1,&ts1,&tm1,&th2,&ts2,&tm2);
employee[i++]=*(newEmployee(tstr,th1,ts1,tm1,th2,ts2,tm2));
}
int j=0;
Employee * first=employee;
Employee * last=employee;
for(;j<m;j++){ //比較這一天內m條記錄中的最早到達者和最晚離開者,兩個函數分別返回類對象指針
if(*first>employee[j])
first=&employee[j];
if(*last<employee[j])
last=&employee[j];
}
first->print();
cout<<" ";
last->print();
cout<<endl;
}
return 0;
}
1.string和char* 之間的聯繫 http://blog.csdn.net/cogbee/article/details/8931838
注意到類Tree的數據成員用的是 char*而不是string,具體他們之間的轉化會出現什麼問題下次會增加。
2.指針與內存空間問題 http://blog.csdn.net/goodlixueyong/article/details/6068631
首先:
分配數組空間語句放在while循環外面時,運行結果發現每次新增加一天記錄後之前的記錄中的證件號碼均被修改爲新增加記錄的值,說明多個類對象的s指針指向了同一塊內存空間,即均指向了tstr數組空間,所以應在每次新建類對象之前,動態爲其分配一塊空間,將分配數組空間語句放到循環內。
另外:
看下面的while循環,循環內有個分配內存的語句。
while(1)
{
char command[100];
printf("請輸入命令:>");
memset(command,0,100);
gets(command);
printf("%s/n",command);
}
那麼它是每次都分配內存,還是隻分配一次內存呢?
經過驗證發現,每當程序執行到右大括號時,command指向的內存都被釋放掉了,然後重新執行到char command[100]時,系統又重新給程序分配了內存。但是需要注意的是,在程序每次運行過程中,程序使用的內存的其實地址都是一樣的。也就是說每次分配了相同位置的內存。