First and foremost: if iterating over the whole list just to delete the desired items, just use list::remove
without the loop. It will do the trick for you.
However when the loop is needed for this or other reason list::erase
is the way to go, however it will require manual iterator adjustments:
See:
https://stackoverflow.com/a/596180/4885321
Regular for loop will not work as expected, because (bad code ahead):
for(auto i = l.begin();
i!=l.end();
++i) //2nd iteration starts, we're incrementing non-existing iterator, UB!
{
if((*i) == myVal) //let's assume it's true for the first element
l.erase(i); //ok, erase it
}
Thus, the right solution should look like this:
while (i != l.end()) {
if (*i == myVal) {
l.erase(i++);
// or i = l.erase(i);
// note: valid iterator is incremented before call to erase thus the new i is valid
// the node pointed to by the old one is removed
} else {
++i;
}
}
I recommend looking up in Meyers's Effective STL for further information on that and related topics.