Jump to content
  • Advertisement
Sign in to follow this  
Stompy9999

Removing an element from an STL list

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

Advertisement
Quote:
Original post by visage
Whack. This says otherwise...which is what I was going by.


You shouldn't believe everything you read on the net. [smile]

Share this post


Link to post
Share on other sites

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
}



This doesn't work correctly; if it does an erase, it will increment the iterator again (by the update statement in the for loop). Look again at the code I posted, I did say 'study carefully'.

Share this post


Link to post
Share on other sites
You are absolutely correct. I hate hastily changing other people's code for this reason. Change it to a while loop and all is good.



std::list<int>::iterator iter = some_list.begin();
while(iter != some_list.end())
{
if(*iter == 1)
some_list.erase(iter++);
else
iter++;
}


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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!