Using std::vector::reserve whenever possible

09 Jun, 2022
In C++ vectors are dynamic arrays. Unlike arrays, they don’t have a fixed size. They can grow or shrink as required. Vectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location. This reallocation of elements helps vectors to grow when required. However, it is a costly operation and time complexity is involved in this step is linear. std::vector class provides a useful function reserve which helps user specify the minimum size of the vector.It indicates that the vector is created such that it can store at least the number of the specified elements without having to reallocate memory.
std::vector::reserve
void reserve(size_type n)
Return Type: none
Arguments: n which denotes the no of elements to be stored in vector

Requests that vector is large enough to store n elements in the least. 
If the current vector capacity is less than n, then reallocation will 
take place. In other cases, reallocation will not happen. Function does
not modify existing elements in the vector
 Each vector object has two parameters–size and capacity. The size denotes the number of elements currently stored in the vector while capacity is the maximum number of elements that the vector can store without reallocation. Evidently capacity >= size. When the vector runs out of space to store new elements i.e when size is becoming greater than capacity, the runtime library will request fresh memory from the heap and once memory is allocated, it will copy all elements in the vector from their old addresses to the newly allocated memory address. A call to the function reserve modifies the capacity parameter of the vector and so the vector requests sufficient memory to store the specified number of elements. Here is a program to demonstrate the performance improvement that can be obtained by using reserve function. In this program, we fill two vectors with a large number of elements and count the time taken to perform this step. For the first vector, we don’t specify the capacity, while for the second vector we specify the capacity using reserve(). 
Time Complexity – Linear O(N)
CPP
// CPP program to demonstrate use of// std::vector::reserve#include <chrono>#include <iostream>#include <vector> using std::vector;using std::cout;using namespace std::chrono; int main(){    // No of characters    int N = (int)1e6;     vector<int> v1, v2;     // Reserve space in v2    v2.reserve(N);     // Start filling up elements in v1    // To measure execution time in C++, refer below    // https://www.geeksforgeeks.org/measure-execution-time-function-cpp/     auto start = high_resolution_clock::now();    for (int i = 0; i < N; ++i)        v1.push_back(i);    auto stop = high_resolution_clock::now();    auto duration = duration_cast<microseconds>(stop - start);     cout << "Method I took " << duration.count() << " microseconds\n";     // Start filling up elements in v2    start = high_resolution_clock::now();    for (int i = 0; i < N; ++i)        v2.push_back(i);    stop = high_resolution_clock::now();    duration = duration_cast<microseconds>(stop - start);     cout << "Method II took " << duration.count()         << " microseconds \n";     return 0;}
Output: (Machine Dependent)
Method I took 18699 microseconds
Method II took 16276 microseconds 
Note: It is guaranteed that reserving space beforehand will take less time than trying to insert the elements without specifying the size of the vector. Further, it adds semantic utility to the code and we get to know at least how large the vector is going to be.
AdityaKumawat1
surinderdawra388
utkarshgupta110092
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Queue in C++ Standard Template Library (STL)
std::find in C++
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL