# Republic Day Insights: Effective Vector Memory Management

## vector memory management

```cpp
#include <iostream>
#include <vector>
int main(){
    std::vector<int> v;
    std::cout<<"Initial Capacity: "<< v.capacity() <<"\n";

    for (int i = 0; i < 10; ++i){
        v.push_back(i);

        std::cout<<" Size: " << v.size()
                 <<" | Capacity: "<< v.capacity()
                 <<" | Address of v[0]: " << &v[0] << "\n";
    }
    return 0;
}
```

This code scales, but it has a problem known as the ***doubling strategy***!

* but, it’s not a problem, basically we all know vector is a dynamic array
    
* but what makes it dynamic is the doubling strategy
    
* the vector starts with 0 initial capacity, then we add 1, so it increase it’s capacity by 1
    
* basically the whole vector moves to new position of size: 1 , now we add another element: 2,
    
* it resizes itself to 1×2 = 2 , not resize but move to a new space with size:2
    
* now another element:3 (here) , it resizes 2×2=4, and so on,
    
* the vector sizes become 0,1,2,4,8,16…
    
* this is a problem for high frequency trading firm
    
* THE SOLUTION(WRONG ONE: My thought) → we use v(10) at the starting of the vector while initializing
    

```cpp
vector<int> v(10);
```

* what’s wrong? it actually makes an array with 10 zeroes initialized
    
* and the element to be added will go to 11th position where size of v: 10×2=20;
    
* LOL
    
* correct approach? *use reverse()*
    

```cpp
vector<int> v;
v.reserve(10);
```

* it tells the compiler, we are expecting 10 values here, until then don’t resize!!!!!
    

## Bye and Jai Shree Ram!
