The Wayback Machine - https://web.archive.org/web/20240527123610/https://www.geeksforgeeks.org/using-stdvectorreserve-whenever-possible/
Open In App

Using std::vector::reserve whenever possible

Last Updated : 31 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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
 
    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.



Previous Article
Next Article

Similar Reads

std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header &lt;iostream&gt;. Use of precision : In the default floati
3 min read
std::oct , std::dec and std::hex in C++
This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in oc
2 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File &lt;string&gt; String Functionalities The
6 min read
std::stod, std::stof, std::stold in C++
std::stod() : It convert string into double. Syntax: double stod( const std::string&amp; str, std::size_t* pos = 0 ); double stod( const std::wstring&amp; str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This param
3 min read
std::setbase, std::setw , std::setfill in C++
The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : std::setbase (int base);decimal : if base is 10hexadecimal : if base is 16octal
3 min read
Difference between std::set vs std::vector in C++ STL
Vectors: Vectors are containers similar to dynamic arrays, with the ability to resize when a new element is inserted or deleted from it. It is a template of Standard Template Library or STL, which provides more flexibility to the program. Elements of vectors are placed in contiguous storage and are traversed using iterators. Examples: vector &lt;in
3 min read
Difference between std::swap and std::vector::swap
The std::swap is a general function used to exchange the given values whereas the std::vector::swap is a specialized function that can swap all the contents of two different vector containers.Below are some major key differences between std::swap and std::vector::swap, std::swapstd::vector::swapThe std::swap() is a built-in function in C++ STL whic
3 min read
std::upper_bound and std::lower_bound for Vector in C++ STL
Click here for Set 1 and Set 2 of Vectors. Vector - upper_bound and lower_boundIterator lower_bound (Iterator first, Iterator last, const val) lower_bound returns an iterator pointing to the first element in the range [first,last) which has a value not less than 'val' and if the value is not present in the vector then it returns the end iterator. I
4 min read
std::tuple, std::pair | Returning multiple values from a function using Tuple and Pair in C++
There can be some instances where you need to return multiple values (maybe of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed here There is another interesting method to do the same without using the above methods,  using tuples (for returning multipl
2 min read
unordered_set reserve() function in C++ STL
The unordered_set::reserve() method is a builtin function in C++ STL which is used to request capacity change of unordered_set. It sets the number of buckets in the container to contain at least n elements. If n is greater than the current bucket_count multiplied by the max_load_factor, the container's bucket_count is increased and a rehash is forc
2 min read
Article Tags :
Practice Tags :