Open In App

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

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

In C++, vectors are dynamic arrays that can resize themselves when more data is needed. But internally, apart from the resizing, the vector also keeps some extra space for expected elements to reduce the time complexity of insertion. The total space accounting for this extra space is called capacity.

In this article, we will learn how to reduce the capacity of the vector to its size in C++.

For Example,

Input:
myVector = {34, 67, 21, 90, 78}
myVector.capacity() = 8

Output:
myVector = {34, 67, 21, 90, 78}
myVector.capacity() = 5

Reducing the Capacity of the Vector to Fit its Size in C++

The std::vector class contains a member function named std::vector::shrink_to_fit() function that is used to shrink the capacity of the vector to its size. We can use it as shown:

myVector.shrink_to_fit();

C++ Program to Reduce the Capacity of the Vector to Fit its Size

C++




// C++ Program to Demonstrate how to shrink the vector
// capacity to fit its size
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Creating a Vector of 20 size
    vector<int> myVector(20);
  
    // Inserting elements in the vector
    myVector = { 1, 2, 3, 4, 5, 5 };
  
    // Display the current size and capacity of vector
    cout << "Capacity: " << myVector.capacity() << endl;
  
    // Reducing the capacity of vector
    myVector.shrink_to_fit();
  
    // Display the updated size and capacity of vector
    cout << "Capacity: " << myVector.capacity() << endl;
  
    return 0;
}


Output

Capacity: 20
Capacity: 6

Time Complexity: O(1)
Space Complexity: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads