Does std::vector.pop_back() change vector's ca

2019-01-17 22:10发布

问题:

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?

回答1:

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

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



回答2:

No. pop_back() will not shrink the capacity of vector. use std::vector<T>(v).swap(v) instead.



回答3:

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:

#include <iostream>
#include <vector>
using namespace std;

int main(){
    vector<int> myVector;

    for (auto i=1;i!=1e3;++i)
        myVector.push_back(i);

    cout << "Capacity: " << myVector.capacity() << endl;
    myVector.reserve(2000);
    cout << "Capacity (after reserving 2000): " << myVector.capacity() << endl;
    myVector.shrink_to_fit();
    cout << "Capacity (after shrink_to_fit): " << myVector.capacity(); 

}


回答4:

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.



回答5:

NO. Same as push_back , pop_back won't impact the capacity(). They just impact the size().

EDIT:

I should have said push_back won't change the capacity when the v.size() < v.capacity().



回答6:

Here is the code of std::vector::pop_back()

void pop_back()
{   // erase element at end
   if (!empty())
   {    // erase last element
      _Dest_val(this->_Alval, this->_Mylast - 1);
      --this->_Mylast;
   }
}

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.