Remove first N elements from a std::vector

孤人 提交于 2019-12-18 10:52:50

问题


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?


回答1:


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);



回答2:


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.




回答3:


v.erase( v.begin(), v.size() > N ?  v.begin() + N : v.end() );

Don't forget the check of the size, just in case.



来源:https://stackoverflow.com/questions/7351899/remove-first-n-elements-from-a-stdvector

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