Jump to content
  • Advertisement
Sign in to follow this  
Stompy9999

Removing an element from an STL list

This topic is 4874 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

How exactly do I remove an element from the middle of an STL list? I know that STL lists are capable of this, but how do I do it? Thanks in advance!

Share this post


Link to post
Share on other sites
Advertisement
To erase one or a range of elements use std::list::erase given a non constant list iterators to what position in the list.

To remove all occurrences of some given key value or criteria use std::list::remove or std::list::remove_if. You can also use std::remove/remove_if then pass the return iterator to std::list::erase and the list's end iterator.

Share this post


Link to post
Share on other sites
I've got another question along these lines. If I were to iterate through a list, and remove an element, could I still continue iterating as normal? For instance, suppose I have a list of integers:


for(std::list<int>::iterator i = some_list.begin(); i != some_list.end(); i++)
{
// After this, can I continue through the list as normal?
if(*i == 1)
some_list.erase(i);

}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
I think you need to get a new iterator from erase(), since it will invalidate the one you have.

So:
i = some_list.erase(i);

Share this post


Link to post
Share on other sites

Study carefully:



for(std::list<int>::iterator iter = some_list.begin(); iter != some_list.end(); )
{
// After this, can I continue through the list as normal?
if(*iter == 1)
iter = some_list.erase(iter);
else
++iter;
}


Share this post


Link to post
Share on other sites
Erase invalidates the iterator you are using. If you increment the iterator in the erase, it will move on to the next item in your list and the erase will work fine.


std::list<int>::iterator iter;
for(iter = some_list.begin(); iter != some_list.end(); iter++)
{
if(*iter == 1)
some_list.erase(iter++); // erase and move to next item in list
}





[Edited by - ascorbic on June 18, 2005 12:09:22 AM]

Share this post


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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!