A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/std-vector-reserve-in-cpp-stl/ below:

Vector reserve() in C++ STL

Vector reserve() in C++ STL

Last Updated : 23 Jul, 2025

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;
}

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 Return 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;
}

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;
}

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



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4