Reserve your space in vector. Serioulsy, DO IT

Reserve your space in vector. Serioulsy, DO IT

Always reserve space for vector in advance if you know the expected size of a vector, this avoids reallocations which happen frequently when a vector gradually grows and breaches available capacity
Note that, every time this breach happens, a new allocation is done which is a costly operation

To understand, why we need to reserve, we need to know the difference between size and capacity of a vector and how does a vector allocate memory dynamically, Read it here, https://cppnuggets.hashnode.dev/size-vs-capacity-in-a-vector

#include <vector>
int main()
{
    // 1. Naive method, without reserve
    std::vector<int> box;
    for( int index = 0; index < 50; index++)
        box.push_back(50);

    // 2. With reserve
    std::vector<int>another_box;
    another_box.reserve(50);
    for( int index = 0; index < 50; index++)
        box.push_back(50);
}

In first method, vector will need to allocate memory dynamically and copy elements to new memory block, whenever limit exceeds.

In second method, with reserve, memory for 50 elements will be allocated in one shot, thus avoiding the need of further allocations. In vector lingo, another_box will be assigned with capacity of 50,
Hence, we wont need further reallocations