[英]C++ | List iterator not incrementable
我试图遍历一个列表,然后,如果对象的车牌号与通过参数指定的车牌号相匹配,并且收费(在toll()中计算)小于或等于给定的美分,请删除/擦除对象从列表中。 我不断收到列表迭代器无法递增的错误,而且对于如何解决它一无所知。
void one_time_payment(string& plate_number, int cents) {
// TODO: REWRITE THIS FUNCTION
std::list<LicenseTrip>:: iterator it;
for (it = listLicense.begin(); it != listLicense.end(); std::advance(it, 1)) {
if (it->plate_number().compare(plate_number) == 0) {
cout << "Matching Plate Found" << endl;
if (it->toll() <= cents) {
cout << "Can be paid" << endl;
it = listLicense.erase(it); //Error: list iterator cannot be incremented
}
}
}
cout << "End of Iterator" << endl;
}
我猜这不是编译错误,而是触发的断言。 你有个bug!
假设您处于最后一个元素,并且所有条件都适用。 因此,我们这样做:
it = listLicense.erase(it);
现在, it
是end()
。 但经过正确的,在的体内循环的结束,我们推进it
! 这是未定义的行为! 因此:列表迭代器无法递增。
为了帮助我们正确地编写此代码,有一个list::remove_if
:
listLicense.remove_if([&](const LicenseTrip& trip){
return trip.plate_number() == plate_number &&
trip.toll() <= cents;
});
所以,巴里解释说,这是造成失败的说法,问题是,迭代器将试图推进it
超越end()
这将使未定义行为。 在我的情况下, it
将只需要一次(仅用于定位LicenseTrip
具有匹配plate_number
),所以它足以把一个break;
在listLicense.erase(it)
。 最终的工作代码如下:
void one_time_payment(string& plate_number, int cents) {
std::list<LicenseTrip>:: iterator it;
for (it = listLicense.begin(); (it != listLicense.end()) ; std::advance(it, 1)) {
if (it->plate_number().compare(plate_number) == 0 && it->toll() <= cents)
if (it->toll() <= cents) {
listLicense.erase(it);
break;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.