Remove first N elements from a std::vector

ForeverLearning picture ForeverLearning · Sep 8, 2011 · Viewed 32.8k times · Source

I can't seem to think of a reliable way (that also compacts memory) to remove the first N elements from a std::vector. How would one go about doing that?

Answer

Mark Ransom picture Mark Ransom · Sep 8, 2011

Since you mention that you want to compact memory, it would be best to copy everything to a new vector and use the swap idiom.

std::vector<decltype(myvector)::value_type>(myvector.begin()+N, myvector.end()).swap(myvector);