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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不。缩小向量容量的唯一方法是交换技巧
,即使这样也不能保证按照标准工作。 (尽管很难想象它不起作用的实现。)
据我所知,C++ 标准的下一个版本(以前是 C++0x,但现在变成了 C++1x)将具有 <代码>std::vector<>::shrink_to_fit()。
No. The only way to shrink a vector's capacity is the swap trick
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.)
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()
.不会。pop_back()不会缩小向量的容量。使用(v).swap(v)。
相反,std::vector
No. pop_back() will not shrink the capacity of vector. use
std::vector<T>(v).swap(v)
instead.在C++11下,可以调用shrink_to_fit()来请求一个向量(以及双端队列或字符串),以便将保留空间减少到向量的容量。但请注意,这取决于实现:这只是一个请求,并且没有任何保证。您可以尝试以下代码:
Under C++11 one can call shrink_to_fit() to ask for a vector (as well as a deque or a string) in order to reduce the reserved space to the vector's capacity. Note however that this is implementation dependent: it's merely a request and there's no guarantee whatsoever. You can try the following code:
不。与
push_back
相同,pop_back
不会影响capacity()
。它们只会影响size()
。编辑:
我应该说,当
v.size()
v.size()
。push_back
时,push_back
不会改变容量。 v.capacity()NO. Same as
push_back
,pop_back
won't impact thecapacity()
. They just impact thesize()
.EDIT:
I should have said
push_back
won't change the capacity when thev.size() < v.capacity()
.pop_XXX 永远不会改变容量。如果您尝试推送超出容量允许的内容,push_XXX 可以更改容量。
pop_XXX will never change the capacity. push_XXX can change the capacity if you try to push more stuff on than the capacity allows.
这是 std::vector::pop_back() 函数的代码,
仅调用析构函数并减少指向最后一个元素的指针。
来自 VC 的代码(发布)。因此它不会影响向量的容量(或重新分配)。
Here is the code of std::vector::pop_back()
Function only calls the Destructor and decreases pointer to the last element.
Code from VC (Release). So it does not affect on capacity (or reallocation) of vector.