jac*_*hab 14 c++ memory-management stl vector
如果我使用resize()
和reserve()
在程序开始时将std :: vector分配给某个大小和容量,是否有pop_back()
可能"破坏"保留容量并导致重新分配?
sbi*_*sbi 19
不可以.缩小矢量容量的唯一方法是交换技巧
template< typename T, class Allocator >
void shrink_capacity(std::vector<T,Allocator>& v)
{
std::vector<T,Allocator>(v.begin(),v.end()).swap(v);
}
Run Code Online (Sandbox Code Playgroud)
甚至不保证按照标准工作.(虽然很难想象一个实现不起作用的实现.)
据我所知,C++标准的下一个版本(曾经是C++ 0x,但现在变成了C++ 1x)将具有std::vector<>::shrink_to_fit()
.