Open In App

How to Increase the Capacity of a Vector in C++?

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, vectors are containers that store data in contiguous memory locations and can resize themselves depending on the number of elements. In this article, we will learn how to increase the capacity of a vector in C++.

For Example,

Input: myVector.capacity() = 8
 
 Output:
// new capacity
myVector.capacity() = 16;

Increase the Capacity of a Vector in C++

A vector’s capacity is the amount of storage it currently has, while its size is the number of elements it has. The std::vector::reserve() function is a simple method to increase the capacity of the vector. We pass the new capacity as an argument to this vector.

Note: std::vector::reserve() never reduces the capacity or size of the vector.

C++ Program to Increase the Capacity of a Vector

C++




// C++ Program to Demonstrate Vector Capacity Increase
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Create vector
    vector<int> arr = { 2, 5, 7, 8 };
  
    // Print the vector's initial capacity
    cout << "Vector Initial Capacity: " << arr.capacity()
         << endl;
  
    // Reserve space for 5 elements
    arr.reserve(5);
  
    // Print the vector's increased capacity
    cout << "Vector Increased Capacity: " << arr.capacity()
         << endl;
  
    return 0;
}


Output

Vector Initial Capacity: 4
Vector Increased Capacity: 5

Time Complexity: O(n), as the memory will be reallocated.
Space Complexity: O(n)

We can also use the std::vector::resize() function but it will only increase the capacity of the vector if the current capacity is less than the desired capacity


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads