Does std::vector.pop_back() change vector#39;s capacity?(std::vector.pop_back() 会改变向量的容量吗?)
问题描述
如果我在程序开始时使用 resize() 和 reserve() 将 std::vector 分配到特定大小和容量,是否有可能pop_back() 可能会破坏"保留容量并导致重新分配?
If I allocated an std::vector to a certain size and capacity using resize() and reserve() at the beginning of my program, is it possible that pop_back() may "break" the reserved capacity and cause reallocations?
推荐答案
没有.缩小向量容量的唯一方法是交换技巧
No. The only way to shrink a vector's capacity is the swap trick
template< typename T, class Allocator >
void shrink_capacity(std::vector<T,Allocator>& v)
{
std::vector<T,Allocator>(v.begin(),v.end()).swap(v);
}
即使这样也不能保证按照标准工作.(虽然很难想象它不会工作的实现.)
and even that isn't guaranteed to work according to the standard. (Although it's hard to imagine an implementation where it wouldn't work.)
据我所知,C++ 标准的下一个版本(以前是 C++0x,但现在变成了 C++1x)将具有 std::vector<>::shrink_to_fit().
As far as I know, the next version of the C++ standard (what used to be C++0x, but now became C++1x) will have std::vector<>::shrink_to_fit().
这篇关于std::vector.pop_back() 会改变向量的容量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::vector.pop_back() 会改变向量的容量吗?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
