Will a call to std::vector::clear() set std::vector::capacity() to zero?(调用 std::vector::clear() 会将 std::vector::capacity() 设置为零吗?)
问题描述
如果我在向量上使用 .reserve(items),向量将分配足够的内存来让我猜测我需要的项目数量.
If I use .reserve(items) on a vector, the vector will allocate enough memory for my guess of the number of items that I'll need.
如果我以后使用 .clear(),这只是清除向量还是保存我之前定义的储备?
If I later on use .clear(), will that just clear the vector or save my earlier defined reserve?
谢谢.
推荐答案
指定 std::vector 影响大小.它可能不会影响容量.要重置容量,请使用交换技巧:
It is specified that std::vector<T>::clear() affects the size. It might not affect the capacity. For resetting the capacity, use the swap trick:
std::vector<int> v1;
// somehow increase capacity
std::vector<int>().swap(v1);
注意:由于这个旧答案仍然得到赞成(因此人们阅读它),我觉得有必要添加C++11 添加了 std::vector<...>::shrink_to_fit(),它请求向量删除未使用的容量.
Note: Since this old answer is still getting upvotes (thus people read it), I feel the need to add that C++11 has added std::vector<...>::shrink_to_fit(), which requests the vector to remove unused capacity.
这篇关于调用 std::vector::clear() 会将 std::vector::capacity() 设置为零吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:调用 std::vector::clear() 会将 std::vector::capacity() 设置为零吗?
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
