如何从std :: vector中删除元素,而不调整它的大小 [英] How to remove element(s) from std::vector without resizing it

查看:1007
本文介绍了如何从std :: vector中删除元素,而不调整它的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


迭代器擦除(迭代器位置);



迭代器擦除(迭代器先,
迭代器最后)

擦除元素从向量
容器中删除单个元素
(position)或元素范围
([first,last)]。



这有效地减少了向量
的大小除以元素数量
删除,调用每个元素的
析构函数。


和:


移除



删除等于
给定值范围内的所有元素,
由[first,last)定义。删除是
通过移动
范围中的元素,以覆盖所需的
元素的方式完成。元素
在旧的和新的结束之间的
范围保持不变。迭代器到
返回范围的新端。


有没有办法从std ::向量在迭代器范围内(类似于删除,但是ALL元素从[第一,最后]),而不调整矢量的大小?我需要保持它在运行时达到的最大大小,以防止realloc。



谢谢!

解决方案

resize 永远不会减少向量的容量 - 你可以安全地使用 erase / p>

使用 reserve 使向量为某一数量的项目预分配空间。除非您实际超过此限制,否则插入擦除 resize 将导致一个realloc。如果超过它,向量将在内部保留更多的空间 - 但它不会减少内部容量。


iterator erase ( iterator position );

iterator erase ( iterator first, iterator last );

Erase elements Removes from the vector container either a single element (position) or a range of elements ([first,last)).

This effectively reduces the vector size by the number of elements removed, calling each element's destructor before.

and:

remove

Removes all elements equaling the given value value from the range, defined by [first, last). Removing is done by shifting the elements in the range in such a way that required elements are overwritten. The elements between the old and the new ends of the range are left intact. Iterator to the new end of the range is returned.

Is there any way to remove elements from a std::vector within an iterator range(something like remove, but ALL elements from [first, last]) without resizing the vector? I need to keep it's maximum size that it reached at runtime to prevent reallocs.

Thanks!

解决方案

resize will never reduce the capacity of the vector - you can safely use erase for this.

Use reserve to make a vector preallocate space for a certain number of items. Unless you actually exceed this limit, no insert or erase or resize will lead to a realloc. If you exceed it, the vector will internally reserve more space - but it will not reduce the internal capacity.

这篇关于如何从std :: vector中删除元素,而不调整它的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆