Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ vector::reserve function is used to reserve the vector capacity be at least enough to contain specified elements (n). If n is greater than the current vector capacity, then the reallocation happens to increase the vector capacity to n (or greater). If n is less than or equal to the vector capacity, then vector capacity remains unaffected.

Syntax

void reserve (size_type n);
void reserve (size_type n);

Parameters

n Minimum capacity for the vector.

Return Value

None.

Time Complexity

Linear i.e, Θ(n) only when the reallocation happens.

Example:

In the below example, the vector::reserve function is used to reserve the capacity of vector vec1 and vec2.

The initial size of vec1 is 0. After inserting first element, the vec1 capacity increases to 1. After inserting second element, its capacity increases to 2 and so on (vector capacity increases in power of two whenever needed).

The reserved capacity for vec2 is 50. Hence, as soon as the first element is inserted in the vector, its capacity becomes to 50.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<char> vec1;
  vector<char> vec2;

  int size = vec1.capacity();
  for(int i=0; i < 50; i++)
  {
    vec1.push_back('x');
    if(size != vec1.capacity())
    {
      size = vec1.capacity();
      cout<<"vec1 capacity changed to: "<<size<<"\n";
    }
  }
 
  cout<<"\n";
  vec2.reserve(50);
  for(int i=0; i < 50; i++)
  {
    vec2.push_back('y');
    if(size != vec2.capacity())
    {
      size = vec2.capacity();
      cout<<"vec2 capacity changed to: "<<size<<"\n";
    }
  }  
  return 0;
}

The output of the above code will be:

vec1 capacity changed to: 1
vec1 capacity changed to: 2
vec1 capacity changed to: 4
vec1 capacity changed to: 8
vec1 capacity changed to: 16
vec1 capacity changed to: 32
vec1 capacity changed to: 64

vec2 capacity changed to: 50

❮ C++ - Vector