I have a problem, I'm trying to delete an element in a string list but it doesn't work for the last position. I would also like to display the position of the iterator with an arithmetic operation.
list l = {"a","b","c", "d"};
for(std::list<string>::iterator it = l.begin(); it != l.end(); it++)
cout << " &l["<< it - l.begin() <<"]: " << &*it << " l["<< it - l.begin() <<"]: " << *it << endl;
cout << endl;
for(std::list<string>::iterator itt = l.begin(); itt != l.end(); itt++){
if(*itt == "d") itt = l.erase(itt);
cout << " &l["<< itt - l.begin() <<"]: " << &*itt << " l["<< itt - l.begin() <<"]: " << *itt << endl;
}
Thank you for your help.
It "doesn't work" because this line will cause itt
to become the end()
iterator when erasing the last element:
if(*itt == "d") itt = l.erase(itt);
Then the for
loop does itt++
before the loop condition check, and incrementing the end()
iterator is undefined behavior.
You need to modify your loop like this:
for (std::list<string>::iterator itt = l.begin(); itt != l.end(); /* */) {
if (*itt == "d") {
itt = l.erase(itt);
} else {
++itt;
}
// You cannot safely access *itt here because it might be l.end()
}