Sign in to follow this  
supagu

stl list erase in a loop

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this