C++ unordered vector erasure
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.
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.
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?
Dumb question, but is there any reason why you aren't pop_back()-ing in the example?Not a dumb question 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
Popular Topics
Advertisement