c++ - 为什么不在 GotW 54 中调整和清除作品?

标签 c++ vector deque gotw

引用文章Gotw 54通过 HerbSutter,他解释了

  1. “收缩以适应”的正确方法 vector 或双端队列和

  2. 完全清除 vector 或的正确方法 双端队列

Can we just use container.resize() and container.clear() for the above task or am I missing something?

最佳答案

vector 包含两种不同的东西:sizecapacity。如果您只是调整 vector,则不能保证容量(保留多少内存)一定会改变。 resize 是一个与您使用了多少有关的操作,而不是 vector 容量有多少。

例如。

size     == how much you are using
capacity == how much memory is reserved
vector<int> v(10);

v.resize(5); // size == 5 but capacity (may or may) not be changed
v.clear()    // size == 0 but capacity (may or may) not be changed

最后,容量不应该在每次操作时都改变,因为那会带来大量的内存分配/释放开销。他是说,如果您需要“解除分配”由 vector 保留的内存,请执行此操作。

关于c++ - 为什么不在 GotW 54 中调整和清除作品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1720953/

相关文章:

c++ - 将 vector 拆分为 block - 这是正确的吗?

python - 从双端队列的后面删除项目

c++ - 在双向链表中搜索

c++ - 更有效地在微 Controller 上对 C++ 进行基准测试

C++标准写法: Does "through all iterators in the range" imply sequentiality?

c++ - 返回语句中 vector 初始化的编译错误

c - 在 C 中反转双链双端队列

c++ - 访问公共(public)继承模板数据成员

c++ - 将 sqlite 原始数据读入 QByteArray

c++ - C++ 中的用户定义类型和 std::vector