You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

vector::erase会降低vector的capacity吗?

Does vector::erase reduce a vector's capacity?

Great question! The short answer is no — vector::erase will not decrease the capacity of your std::vector. It only modifies the container's size by removing elements, but the underlying allocated memory (which defines the capacity) stays exactly the same.

Let’s refer to the official documentation details to back this up:

从容器中移除指定元素。1) 移除pos位置的元素。2) 移除[first; last)范围内的元素。
会使erase操作点及之后的迭代器和引用失效,包括end()迭代器。
迭代器pos必须是有效的且可解引用的。因此end()迭代器(有效但不可解引用)不能用作pos的值。
若first==last,迭代器first无需可解引用:移除空范围为无操作。

Notice that none of these points mention any adjustment to the vector's capacity. When you call erase, the implementation just shifts the remaining elements left to fill the gap created by the removed ones — it doesn't free any of the previously allocated memory.

If you do want to reduce the capacity to match the current size (to free up unused memory), you have to do this explicitly. Two common approaches are:

  • Use shrink_to_fit(): This is a non-binding request to the compiler to reduce capacity to match size (most modern compilers will honor this request).
  • The swap trick: Create a temporary vector that takes ownership of your current vector's data, then swap them. This guarantees a capacity equal to the current size:
std::vector<int> my_vec = {1,2,3,4,5};
my_vec.erase(my_vec.begin() + 2, my_vec.end()); // Size is now 2, capacity remains 5

// Swap trick to reduce capacity
std::vector<int> temp(std::move(my_vec));
my_vec.swap(temp); // Now my_vec has size 2 and capacity 2

内容的提问来源于stack exchange,提问作者themagicalyang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:07:41