Remove first N elements from a std::vector
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);
Use the .erase()
method:
// Remove the first N elements, and shift everything else down by N indices
myvec.erase(myvec.begin(), myvec.begin() + N);
This will require copying all of the elements from indices N+1 through the end. If you have a large vector and will be doing this frequently, then use a std::deque
instead, which has a more efficient implementation of removing elements from the front.
v.erase( v.begin(), v.size() > N ? v.begin() + N : v.end() );
Don't forget the check of the size, just in case.