std::vector resize downward(std::vector 向下调整大小)
问题描述
C++ 标准似乎没有声明任何一方对容量的副作用resize(n)
,用 n
clear()
.
The C++ standard seems to make no statement regarding side-effects on capacity by either
resize(n)
, with n < size()
, or clear()
.
它确实声明了 push_back
和 pop_back
- O(1)
It does make a statement about amortized cost of push_back
and pop_back
- O(1)
我可以设想一个执行通常类型的容量更改的实现ala CLRS 算法(例如,放大时加倍,将 size 减小到 < capacity()/4
时减半).(Cormen Lieserson Rivest Stein)
I can envision an implementation that does the usual sort of capacity changes
ala CLRS Algorithms (e.g. double when enlarging, halve when decreasing size to < capacity()/4
).
(Cormen Lieserson Rivest Stein)
有人有任何实施限制的参考吗?
Does anyone have a reference for any implementation restrictions?
推荐答案
以较小的尺寸调用 resize()
对 vector
的容量没有影响.它不会释放内存.
Calling resize()
with a smaller size has no effect on the capacity of a vector
. It will not free memory.
从 vector
释放内存的标准习惯用法是用一个空的临时 vector
swap()
它: std::vector
.如果要向下调整大小,则需要从原始向量复制到新的局部临时向量,然后将结果向量与原始向量交换.
The standard idiom for freeing memory from a vector
is to swap()
it with an empty temporary vector
: std::vector<T>().swap(vec);
. If you want to resize downwards you'd need to copy from your original vector into a new local temporary vector and then swap the resulting vector with your original.
更新: C++11 添加了一个成员函数 shrink_to_fit()
出于此目的,这是一个将 capacity()
减少到 size()
的非绑定请求.
Updated: C++11 added a member function shrink_to_fit()
for this purpose, it's a non-binding request to reduce capacity()
to size()
.
这篇关于std::vector 向下调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::vector 向下调整大小
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01