C++ 从 std::vector 中删除前 N 个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7351899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove first N elements from a std::vector
提问by ForeverLearning
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?
我似乎想不出一种可靠的方法(也可以压缩内存)从std::vector
. 怎么会去做呢?
回答by 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);
回答by Adam Rosenfield
Use the .erase()
method:
使用.erase()
方法:
// 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.
这将需要从索引 N+1 到末尾复制所有元素。如果您有一个很大的向量并且会经常这样做,那么请改用 a std::deque
,它可以更有效地实现从前面删除元素。
回答by James Kanze
v.erase( v.begin(), v.size() > N ? v.begin() + N : v.end() );
Don't forget the check of the size, just in case.
不要忘记检查尺寸,以防万一。