std :: vector.pop_back()改变向量的容量? [英] Does std::vector.pop_back() change vector's capacity?

查看:910
本文介绍了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()改变向量的容量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆