How to Reduce the Capacity of a Vector to Fit Its Size in C++?
Last Updated :
05 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector(20);
myVector = { 1, 2, 3, 4, 5, 5 };
cout << "Capacity: " << myVector.capacity() << endl;
myVector.shrink_to_fit();
cout << "Capacity: " << myVector.capacity() << endl;
return 0;
}
|
Output
Capacity: 20
Capacity: 6
Time Complexity: O(1)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...