Open In App

Vector reserve() in C++ STL

Last Updated : 20 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, vector reserve() is a built-in function that reserves the memory for at least a specified number of elements in the vector. It changes the capacity of the vector such that you can add at least the specified number of elements without triggering the internal memory reallocation.

Let’s take a quick look at an example that illustrates vector reserve() method:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v;
    
    // Increase the capacity of vector
    v.reserve(9);
    cout << v.capacity();
  
    return 0;
}

Output
Capacity: 9

This article covers the syntax, usage, and common examples of vector reserve() method in C++:

Syntax of Vector reserve()

The vector reserve() is the member method of std::vector class defined inside <vector> header file.

v.reserve(n);

Parameters

  • n: Number of elements for which the memory is to be reserved.

Return Value

  • This function does not return any value.

Examples of vector reserve()

The following examples demonstrates the use of vector reserve() method for different scenarios and purposes:

Increase the Capacity of Vector

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v(5);
    
    // Capacity initially
    cout << v.capacity() << endl;

    // Increase the capacity of vector
    v.reserve(9);

    cout << v.capacity();
    return 0;
}

Output
5
9

Explanation: Initially the capacity of vector is 5, with vector reserve() we increase the capacity of vector to 9.

Decrease the Capacity of Vector

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v(5);

    // Increase the capacity of vector
    v.reserve(9);
  
  	// Decrease the capacity
  	v.reserve(7);

    cout << v.capacity();
  
    return 0;
}

Output
Final Capacity: 9

Explanation: The vector reserve() method increase the capacity of vector, but cannot not decrease it.


Practice Tags :

Similar Reads