在 C++ 中,方法 resize
(std::vector
)更改 vector 的大小(并在必要时构造/销毁对象), Reserve
允许最终增加 vector 的容量。 shrink_to_fit
将减少 vector 的容量以匹配其大小。当增加 vector 大小时(通过resize
、push_back
或insert
),如果需要,容量将增加(每次需要时容量都会增加一倍)如果我没记错的话,会增加)。
标准是否确保 vector 永远不会减少其容量,除非调用函数 shrink_to_fit
?或者 vector 容量是否可能会根据编译器认为明智的做法而变化?
最佳答案
不, vector 的容量不会因保留
或调整大小
而减少。
If
new_cap
is [not greater thancapacity
] ... no iterators or references are invalidated.
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.
关于c++ - `resize`减少 vector 容量会有风险吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49214902/