C++ unordered vector erasure

Started by
5 comments, last by latent 12 years, 5 months ago
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.
I trust exceptions about as far as I can throw them.
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 );
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.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
In bulk erasures you can use the remove-erase idiom with partition in place of remove.

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?
clb: At the end of 2012, the positions of jupiter, saturn, mercury, and deimos are aligned so as to cause a denormalized flush-to-zero bug when computing earth's gravitational force, slinging it to the sun.
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.
I've thought about asking this question numerous times, glad I'm not alone in wondering what other folks are doing in this case ;)

This topic is closed to new replies.

Advertisement