How to Reduce the Capacity of a Vector in C++?
Last Updated :
12 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec = { 1, 2, 3, 4, 5 };
cout << "Original capacity: " << vec.capacity() << "\n" ;
for ( int i = 6; i <= 10; ++i) {
vec.push_back(i);
}
cout << "Capacity after adding elements: "
<< vec.capacity() << "\n" ;
vec.resize(5);
cout << "Capacity after removing elements: "
<< vec.capacity() << "\n" ;
vec.shrink_to_fit();
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
Share your thoughts in the comments
Please Login to comment...