Remove first N elements from a std::vector

谁说我不能喝 提交于 2019-11-30 00:06:21
Mark Ransom

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!