void handle_arrival(stack
void handle_departure(stack
int main(int argc, char* argv[]) {
//如果没有data.txt参数,程序退出
if (argc != 2) {
cerr << "Usage:\n" << argv[0] << " data-file";
return EXIT_FAILURE;
}
//data.txt不能打开。程序异常退出
ifstream inf(argv[1]);
if (! inf) {
cerr << "Could not open " << argv[1];
return EXIT_FAILURE;
}
//读入data.txt
try {
//关键的定义栈,停车场栈
stack
//直到文件末尾
while (! inf.eof()) {
//注意是按词读取
string action, plate;
inf >> plate >> action;
//根据第二个词采用不同函数处理
if (action == "arrives") {
handle_arrival(parking_lot, plate);
} else if (action == "departs") {
handle_departure(parking_lot, plate);
} else {
cerr << "Unknown action: " << action << endl;
}
}
inf.close();
// Handle any cars that remain in the lot.
while (! parking_lot.empty()) {//当栈不为空
//得到栈顶的车
string plate = parking_lot.top()->get_license_plate();
//处理剩下的车 handle_departure(parking_lot, plate);
}
return EXIT_SUCCESS;
} catch (exception& e) {
cerr << e.what() << endl;
if (inf.is_open()) inf.close();
} catch (...) {
cerr << "Unknown exception caught!" << endl;
if (inf.is_open()) inf.close();
}
return EXIT_FAILURE;
}
void handle_arrival(stack
//判断是否栈满
if ((int) parking_lot.size() == NUMBER_OF_PARKING_SPOTS) {
//满则输出警告
cout << "Sorry " << plate << ", the lot is full\n";
} else {
//不满则创建Car对象再用Stack的push方法进栈
Car* arriving_car = new Car(plate);
parking_lot.push(arriving_car);
}
}
void handle_departure(stack
stack
//当栈顶的型号和要退出的不一致时,让顶部的先出去再压入另外的那个临时栈
while (parking_lot.top()->get_license_plate() != plate) {
//车移动次数加一,直到和参数的plate相同,然后把栈顶的那个车拿出来
parking_lot.top()->times_moved()++;
//把停车场栈顶的车压入临时栈
the_street.push(parking_lot.top());
//停车场栈顶出栈
parking_lot.pop();
}
//栈顶的车并输入它的型号和移动次数
Car* departing_car = parking_lot.top();
cout << departing_car->get_license_plate() << " was moved "
<< departing_car->times_moved() << " times while it was here\n";
//栈顶的车出栈
parking_lot.pop();
//把已经出栈的车给删除了
delete departing_car;
//然后再把临时栈的车全部按那个顺序再放回停车场栈即可
while (! the_street.empty()) {
//临时栈顶放入停车场栈
parking_lot.push(the_street.top());
//临时栈顶出车
the_street.pop();
}
}这样这个题就算完成了,相信你也对STL的栈有了些认识,所以继续努力吧
最后附上data.txt的内容
//data.txt
COOLONE arrives
COOLONE departs
TKG-123 arrives
QWE-839 arrives
UTU-K90 arrives
QWE-839 departs
RRR-877 arrives
GHL-GII arrives
PROGRAM arrives
TKG-123 departs
HEAD-DR arrives
UTU-K90 departs
RRR-877 departs
DMS-RJS arrives
DMS-RJS departs
TUE-87B arrives
GHL-GII departs
WEW-GH1 arrives
THE-MAN arrives
PORSCHE arrives
HEAD-DR departs
ERU-883 arrives
TUE-87B departs
WEW-GH1 departs
APPLE-1 arrives
BKE-284 arrives
BKE-284 departs
APPLE-1 departs
THE-MAN departs