`resize` 会降低矢量容量吗?

Will `resize` have any risk to reduce the vector capacity?

在 C++ 中,方法 resize(属于 std::vector),更改向量的大小(并在必要时构造/销毁对象),reserve 允许最终增加向量的容量。 shrink_to_fit 将减少矢量的容量以匹配其大小。当增加矢量大小时(通过 resizepush_backinsert),容量将根据需要增加(如果我没记错的话,每次需要增加时容量都会加倍)。

标准是否确保 vector 永远不会减少其容量,除非调用函数 shrink_to_fit?或者向量容量是否有可能根据编译器认为明智的做法而变化?

不,矢量的容量不会减少 reserveresize

std::vector::reserve:

If new_cap is [not greater than capacity] ... no iterators or references are invalidated.

std::vector::resize

Vector capacity is never reduced when resizing to smaller size because that would invalidate all iterators, rather than only the ones that would be invalidated by the equivalent sequence of pop_back() calls.

Relevant part of the standard