vendredi 17 juillet 2020

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

I've just started with C++ stl's and the first thing i started is vectors. I've a bit confusion with the capacity in vectors. 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. Can someone kindly explain me the internal working? I'm a bit confused.

#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

Aucun commentaire:

Enregistrer un commentaire