while (true) { flag = 0; prefix("退票办理"); cout << " 请输入航班号:"; cin >> answer; for (auto& flight : v) { if (flight.Flight_No == answer) { cout << " 请输入您的姓名:"; cin >> name; for (auto it = flight.CustName.Name.begin(); it != flight.CustName.Name.end(); ++it) { if (it== name) { flag = 1; Seat_No = flight.CustName.Seat_No; flight.CustName.erase(it); flight.Free_Amount += 1; flight.CustNo -= 1; Customer_Count--; if (Customer_Count == 0) { IsEmpty = 1; } break; }怎么改呢
时间: 2024-02-10 07:27:09 浏览: 78
运算符重载 << >>流插入符 流提取符
这段代码存在一些问题。首先,`it == name` 是错误的比较方式,因为`it`是迭代器,而`name`是一个字符串。正确的比较方式应该是 `*it == name`。其次,删除元素后继续使用迭代器是不安全的,会导致未定义行为。应该使用 `it = flight.CustName.Name.erase(it)` 来删除元素并重新赋值给迭代器。最后,在找到匹配的姓名后,应该立即退出内层循环,而不是继续遍历剩余的姓名。
修正后的代码如下:
```cpp
while (true) {
flag = 0;
prefix("退票办理");
cout << " 请输入航班号:";
cin >> answer;
for (auto& flight : v) {
if (flight.Flight_No == answer) {
cout << " 请输入您的姓名:";
cin >> name;
for (auto it = flight.CustName.Name.begin(); it != flight.CustName.Name.end(); ++it) {
if (*it == name) {
flag = 1;
Seat_No = flight.CustName.Seat_No;
it = flight.CustName.Name.erase(it);
flight.Free_Amount += 1;
flight.CustNo -= 1;
Customer_Count--;
if (Customer_Count == 0) {
IsEmpty = 1;
}
break;
}
}
if (flag == 1) {
break;
}
}
}
// 其他后续处理...
}
```
这样修正后,代码在找到匹配的航班和姓名后会立即退出循环,并且安全地删除姓名。
阅读全文