• Advertisement
Sign in to follow this  

stl list erase in a loop

This topic is 4361 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

i want to remove elements from a list in a loop if they meet a certain criteria. ie. they time out so i have a loop pesdudo code: for (it = begin; it != end; ++it) { if (timed out) { erase(it) continue; } do other stuff with the iterator } problem is, it dies saying it cant increment the iterator after its been erased. is there a way this can be done? currently i've had to hack t so it if times out it breaks out of the loop, which could be bad!

Share this post


Link to post
Share on other sites
Advertisement
You could use std::list::remove_if() instead of manually erasing.

Share this post


Link to post
Share on other sites
Hey bud,

Set a temporary iterator to the next node, delete then current iterators node, then switch the next iterator to the current one and repeat the process.

Hope that helps,

Dave

Share this post


Link to post
Share on other sites
Quote:
Original post by Dave
Hey bud,

Set a temporary iterator to the next node, delete then current iterators node, then switch the next iterator to the current one and repeat the process.

Hope that helps,

Dave

The STL designers already thought of that. That's why erase() returns an iterator to the next element after the erased one, or returns end() if the item erased was the last one. So all you need to do is set the current iterator to the return value of erase() if you are removing the element, or increment the iterator if you're keeping the element.
Iterator = Container.begin();
while (Iterator != Container.end())
{
if (Iterator->IsTimedOut(CurrentTime))
{
Iterator = Container.erase(Iterator);
}
else
{
//do other stuff with the iterator
++Iterator;
}
}

Share this post


Link to post
Share on other sites
Quote:
Original post by Agony
Quote:
Original post by Dave
Hey bud,

Set a temporary iterator to the next node, delete then current iterators node, then switch the next iterator to the current one and repeat the process.

Hope that helps,

Dave

The STL designers already thought of that. That's why erase() returns an iterator to the next element after the erased one, or returns end() if the item erased was the last one. So all you need to do is set the current iterator to the return value of erase() if you are removing the element, or increment the iterator if you're keeping the element.
Iterator = Container.begin();
while (Iterator != Container.end())
{
if (Iterator->IsTimedOut(CurrentTime))
{
Iterator = Container.erase(Iterator);
}
else
{
//do other stuff with the iterator
++Iterator;
}
}


Ok ty, i have never needed to do this kind of erasing on a list.

Dave

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement