Jump to content
  • Advertisement
Sign in to follow this  
DaTroof

C++: Erasing Elements in a Set

This topic is 4651 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 have a routine that iterates through a set of object pointers, and performs a function that determines whether the element should be removed. It looks something like this:
set<foo*>::iterator i = container.begin();
foo* bar;
while (i != container.end()) {
        bar = *i;
	if (bar->execute() == 0) {
		i++;
	} else {
		container.erase(i);
		i = container.upper_bound(bar);
	}
}

This is the best way I could conceive to remove elements from the set while iterating through it, the main problem being that I don't see another way to keep the iterator valid after the erase(). Is there a better method?

Share this post


Link to post
Share on other sites
Advertisement
Not in for std::set in standard C++, though some vendors have std::set::erase() return an iterator anyways. Anyways one way to handle this is to make a copy of the iterator, increment that and then erase the old iterator.

Share this post


Link to post
Share on other sites
Quote:
Original post by SiCrane
Not in for std::set in standard C++, though some vendors have std::set::erase() return an iterator anyways. Anyways one way to handle this is to make a copy of the iterator, increment that and then erase the old iterator.


Yes, the std::set::erase() I'm using doesn't return an iterator. Copying the iterator is probably more efficient than an upper_bound check, so I'll try that instead. Thanks.

Share this post


Link to post
Share on other sites
You could maintain iterator to previous element (prev_i, initially container.end()) and do:

if(prev_i==container.end())
i=container.begin();
else
{
i=prev_i;
++i;
}




once it's being removed from the set.

Edit: Or what SiCrane suggested. It's actually better option.

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!