Jump to content
  • Advertisement
Sign in to follow this  
Storyyeller

C++ unordered vector erasure

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

For a standard vector, random access erasures are linear time, due to shifting all the elements. However, sometimes you don't care about ordering, so you instead want to do a constant time erasure by swapping with the final element and then removing it. Is there any standard implementation of this? It seems like a common task, but I couldn't find anything by googling.

Share this post


Link to post
Share on other sites
Advertisement
Not sure if there's a standard algorithm for it, but it's only two lines of code:std::swap( container.back(), *iterator );
container.resize( container.size()-1 );

Share this post


Link to post
Share on other sites
It may be common enough, but it's still only a two line task. AFAIK everyone just writes the two lines, possibly putting them into their own function.

Share this post


Link to post
Share on other sites

Not sure if there's a standard algorithm for it, but it's only two lines of code:std::swap( container.back(), *iterator );
container.resize( container.size()-1 );



Dumb question, but is there any reason why you aren't pop_back()-ing in the example?

Share this post


Link to post
Share on other sites
Dumb question, but is there any reason why you aren't pop_back()-ing in the example?
Not a dumb question tongue.gif I wrote that code off the top of my head and apparently had forgotten about [font="'Courier New"]pop_back[/font]; using it would indeed be clearer and more succinct.

Share this post


Link to post
Share on other sites
I've thought about asking this question numerous times, glad I'm not alone in wondering what other folks are doing in this case ;)

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!