List: Erase element at iterator during iterations
I em having trouble with a list iteration.
I have to tranverse a list rather frequently, if an element is flagged for deletion then it must be removed.
for (list<int> iter = l.begin(); iter != l.end(); ++iter)
{
iter = l.erase(iter);
cout << (*iter) << endl;
}
This deletes every even number... since the first element is deleted, the 2nd is returns, then it is incremented by the for loop and deleted.
Re: List: Erase element at iterator during iterations
Increment "manually"
for (iter = l.begin(); iter!=l.end();)
{
if (must erase)
iter = l.erase(iter);
else
++iter;
}
Re: List: Erase element at iterator during iterations
go through the list backwards
for (list<int> iter = l.end(); iter != l.begin(); --iter)
{
l.erase(iter);
cout << (*iter) << endl;
}
Re: List: Erase element at iterator during iterations
This will not work, when you call l.erase(iter) the iterator becomes invalid, any other action with that iterator is illegal.
The idiomatic C++ way to do what you want to do is using list::remove_if. An alternative is to increment the iterator before erasing it:
Code:
for (list<int>::iterator iter = l.begin(); iter != l.end(); )
{
list<int>::iterator to_erase = iter;
++iter;
if (i_want_to_erase_it) {
iter = l.erase(to_erase);
}
}
Re: List: Erase element at iterator during iterations
twanvl && bilm_ks methods worked fine with the expected results.
Now, twanvl your method works identically to bilm_ks, I cannot see why your method is more "correct".
If you go iter = l.erase(iter). The returned iterator is valid.
If you do not erase then ++iter.
So
while (iter != l.end())
{
if (erase) iter = l.erase(iter);
else ++iter;
}
Re: List: Erase element at iterator during iterations
Indeed, bilm_ks's method is also recommended by Scott Meyers in Effective STL.
But twanvl is right, remove_if would be the typical way to do this.