简体   繁体   中英

size() and capacity() of c++ vectors

I've just started with C++'s standard library and the first thing I started with is std::vector . I've a bit of confusion with the capacity() in a vector. I know that after each push_back() , the capacity of the vector changes in exponential powers, but in the below output the capacity remains the same value sometimes, even after insertions. Can someone kindly explain to me the internal working?

#include<iostream>
#include<vector>

using namespace std;

int main(){
    vector<int> v;
    int capacity=v.capacity();
    cout<<"Capacity before push_back(): "<<capacity<<endl;
    for(int i=0;i<10;i++){
        v.push_back(i);
        cout<<"Capacity: "<<v.capacity()<<endl;
        
    }
    for(auto j=v.begin();j!=v.end();j++){
        cout<<*j<<endl;
    }
     
    cout<<"Size of vector: "<<v.size()<<endl;
    cout<<"Final Capacity of vector: "<<v.capacity()<<endl;
    
    return 0;
}

OUTPUT:

Capacity before push_back(): 0
Capacity: 1
Capacity: 2
Capacity: 4
Capacity: 4
Capacity: 8
Capacity: 8
Capacity: 8
Capacity: 8
Capacity: 16
Capacity: 16
0
1
2
3
4
5
6
7
8
9
Size of vector: 10
Final Capacity of vector: 16

I know that after each push_back() the capacity of the vector changes in exponential powers but in the above OUTPUT the capacity is still remaining same sometimes even after insertion.

When capacity is greater than the size after insertion, the capacity doesn't need to, and is guaranteed not to change.

This strategy allows sequential push back to have constant complexity (amortised).

From Vector : [emphasis added]

The storage of the vector is handled automatically, being expanded and contracted as needed. Vectors usually occupy more space than static arrays, because more memory is allocated to handle future growth. This way a vector does not need to reallocate each time an element is inserted, but only when the additional memory is exhausted. The total amount of allocated memory can be queried using capacity() function. Extra memory can be returned to the system via a call to shrink_to_fit(). (since C++11)

I know that after each push_back() , the capacity of the vector changes in exponential powers , but in the below output the capacity remains the same value sometimes, even after insertions.

This is where your misunderstanding lies. The vector's CAPACITY does not increase on every insert, its SIZE increases instead. The CAPACITY grows when an insertion causes the SIZE to increase beyond the current CAPACITY , or if you explicitly request the CAPACITY to increase by calling the reserve() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM