I am trying to iterate through a list and then, if the object's plate number matches the one given through the parameters, and if the toll (calculated in toll()) is less than or equal to the given cents, remove/erase the object from the list. I keep getting the error that the list iterator cannot be incremented and I'm clueless as to how to fix it.
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;
}
This is, I'm guessing, not a compile error but rather an assertion that triggered. You have a bug!
Let's say you're on the last element, and all your conditions apply. So we do:
it = listLicense.erase(it);
Now, it
is end()
. But right after that, at the end of the body of the for loop, we advance it
! This is undefined behavior! Hence: list iterator cannot be incremented.
To help us write this correctly, there is a list::remove_if
:
listLicense.remove_if([&](const LicenseTrip& trip){
return trip.plate_number() == plate_number &&
trip.toll() <= cents;
});