gpt4 book ai didi

c++ - 如何在不调整大小的情况下从 std::vector 中删除元素

转载 作者:可可西里 更新时间:2023-11-01 15:45:57 26 4
gpt4 key购买 nike

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.

和:

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.

有没有办法在不调整 vector 大小的情况下从迭代器范围内的 std::vector 中删除元素(类似于删除,但是 [first, last] 中的所有元素)?我需要保持它在运行时达到的最大大小以防止重新分配。

谢谢!

最佳答案

resize 永远不会减少 vector 的capacity - 你可以安全地使用 erase 来做到这一点。

使用reserve 为一定数量的项目制作 vector 预分配空间。除非您实际超过此限制,否则 inserteraseresize 都不会导致重新分配。如果超过它, vector 将在内部保留更多空间 - 但它不会减少内部容量。

关于c++ - 如何在不调整大小的情况下从 std::vector 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5496692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com