Quantcast
Viewing all articles
Browse latest Browse all 47

Answer by Jeremy for C++ efficient way to remove first x elements, push the x+1th element to the first without changing vector size

vector::erase() doesn't reallocate, it only moves contents within the already-allocated capacity and adjusts the size. (Note that erase() doesn't throw bad_alloc, only copy/move/assignment exceptions. EDIT: That's not really relevant to this scenario.)

So calling erase() should be no less efficient than calling rotate().

erase() is probably more efficient, in fact, since rotate() not only moves the data that in your particular case you want to preserve, but also the data you're about to throw away - but which the semantics of rotate() dictate must also be preserved (which in turn probably necessitates either temporary storage or one-by-one movement). You can hope the optimiser manages to deal with this, or you can call erase().

Of course, the only real way to tell is to implement, measure, and compare.


Viewing all articles
Browse latest Browse all 47

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>