Open In App

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

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

In C++, vectors are dynamic arrays that can grow and reduce in size as per requirements. It also keeps some space for expected elements. This total space is called the capacity of the vector. In this article, we will learn how we can reduce the capacity of a vector in C++.

Example

Input:
myVector.capacity() = 10

Output:
myVector.capacity() = 5

Reduce the Capacity of a Vector in C++

We can use the std::vector::shrink_to_fit( ) function to reduce the capacity and make it equal to the number of elements present in the vector.

Syntax of shrink_to_fit()

vector_name.shrink_to_fit( )

C++ Program to Reduce the Capacity of a Vector

C++




// C++ program to demonstrate how to reduce the capacity of the vector
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initialize a vector
    vector<int> vec = { 1, 2, 3, 4, 5 };
  
    // Output the original capacity of the vector
    cout << "Original capacity: " << vec.capacity() << "\n";
  
    // Add some elements to the vector
    for (int i = 6; i <= 10; ++i) {
        vec.push_back(i);
    }
  
    // Output the capacity after adding elements
    cout << "Capacity after adding elements: "
         << vec.capacity() << "\n";
  
    // Remove some elements from the vector
    vec.resize(5);
  
    // Output the capacity after removing elements
    cout << "Capacity after removing elements: "
         << vec.capacity() << "\n";
  
    // Reduce the capacity of the vector
    vec.shrink_to_fit();
  
    // Output the capacity after shrinking
    cout << "Capacity after shrink_to_fit: "
         << vec.capacity() << "\n";
  
    return 0;
}


Output

Original capacity: 5
Capacity after adding elements: 10
Capacity after removing elements: 10
Capacity after shrink_to_fit: 5


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads