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