c++ - `resize`减少 vector 容量会有风险吗?

标签 c++ memory vector memory-management std

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

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

最佳答案

不, vector 的容量不会因保留调整大小而减少。

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

关于c++ - `resize`减少 vector 容量会有风险吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49214902/

相关文章:

linux - 64 位 Linux 中的交换空间

c++ - 如何根据第一个 vector 的变化对双 vector 进行排序?

r - 将数据帧行转换为字符向量时出错

c++ - 使用不带 resize() 部分的相同 vector

C++ 11 move 语义

c++ - 使用循环停止 QThread 的正确方法(从 opencv 读取视频)

c++ - fstream 的问题读取正常但不写入用户输入字符串

c++ - fork C++ 上父子之间的共享内存

windows - 内存映射文件可选写入可能吗?

c++ - 如何将函数转换为 lambda 函数