pop_back()可以减少向量的容量吗? (C ++) [英] Can pop_back() ever reduce the capacity of a vector? (C++)

查看:287
本文介绍了pop_back()可以减少向量的容量吗? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据C ++标准,是否允许 std :: vector< T> :: pop_back()减少矢量的容量?

According to the C++ standard, is std::vector<T>::pop_back() ever allowed to reduce the capacity of the vector?

我之所以问是因为我想保证,以下代码将抛出内存不足异常:

I am asking because I would like to have a guarantee, that the following code will not throw an out of memory exception:

my_vec.pop_back();
if (...)
    my_vec.push_back(...);

假设 my_vec std :: vector< int>

我想有三种可能性:


  1. 是的,根据C ++ 03和C ++ 11均可发生。

  1. Yes, this can happen according to both C++03 and C++11.

否,C ++ 11禁止这样做(但C ++ 03禁止)。

No, C++11 prohibits this (but C++03 does not).

否,C ++ 03和C ++ 11都禁止

No, both C++03 and C++11 prohibits this.

是的,我的问题与 std :: vector.pop_back()会更改矢量的容量吗?,但是我的问题特别是关于该标准所保证的内容。

Yes, my question is related to Does std::vector.pop_back() change vector's capacity?, but my question is specifically about what the standard guarantees.

另请注意, std :: vector.pop_back()是否更改矢量的容量?主要是关于如何减小矢量的容量,而不是何时保证不发生,并且没有提供有关pop_back()的声明的证据。

Note also that the accepted answer in Does std::vector.pop_back() change vector's capacity? is mostly about how to reduce the capacity of a vector, not about when it is guaranteed not to happen, and offers no evidence for its claim about pop_back().

推荐答案

根据 http://en.cppreference.com/w/cpp/container/vector/pop_back


back() end外,没有迭代器或引用()无效。

因此它可能不会重新分配。该页面上没有 C ++ 11 标记,这意味着在03中也是如此。为完整起见,我将挖掘节的引用并对其进行编辑。

Therefore it may not reallocate. There is no C++11 tag on that page, which implies this is also true in 03. I will dig up the section references and edit them in for completeness.

编辑:更好的是:从 C ++ 03 :[lib.container.requirements ](23.1),第10段:

Even better: From C++03: [lib.container.requirements] (23.1), paragraph 10:


no erase() pop_back() pop_front()函数引发异常。

N3337中的措辞与23.2.1 / 10相同(〜 C ++ 11 )。

Same wording at 23.2.1/10 in N3337 (~C++11).

这篇关于pop_back()可以减少向量的容量吗? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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