Does std::vector.pop_back() change vector's capacity?

后端 未结 6 1535
情深已故
情深已故 2020-12-09 11:04

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

相关标签:
6条回答
  • 2020-12-09 11:22

    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.

    0 讨论(0)
  • 2020-12-09 11:26

    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(); 
    
    }
    
    0 讨论(0)
  • 2020-12-09 11:27

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

    0 讨论(0)
  • 2020-12-09 11:32

    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.

    0 讨论(0)
  • 2020-12-09 11:45

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

    0 讨论(0)
  • 2020-12-09 11:48

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

    0 讨论(0)
提交回复
热议问题