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

后端 未结 6 1563
情深已故
情深已故 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: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 
    #include 
    using namespace std;
    
    int main(){
        vector 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(); 
    
    }
    

提交回复
热议问题