Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can pop_back() ever reduce the capacity of a vector? (C++)

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(...);

Assume that my_vec is an std::vector<int>.

I guess there are three possibilities:

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

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

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

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.

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().

like image 486
Kristian Spangsege Avatar asked May 20 '14 16:05

Kristian Spangsege


People also ask

How do you reduce the capacity of a vector?

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector.

Does erase change vector capacity?

No. That's implied by the fact that iterators, pointers and references prior to the point of erase remain valid. Reducing the capacity would require a reallocation.

Does Pop_back reduce vector size?

C++ pop_back() function is used to pop or remove elements from a vector from the back. The value is removed from the vector from the end, and the container size is decreased by 1. 1.

Does Push_back increase size of vector?

push_back effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call.


1 Answers

According to http://en.cppreference.com/w/cpp/container/vector/pop_back

No iterators or references except for back() and end() are invalidated.

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.

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

no erase(), pop_back() or pop_front() function throws an exception.

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

like image 78
BoBTFish Avatar answered Sep 28 '22 06:09

BoBTFish