vector shrink_to_fit() function in C++ STL
The vector::shrink_to_fit() is a built-in function in C++ STL which reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.
Syntax:
vector_name.shrink_to_fit()
Parameters: The function does not accept any parameters.
Return value: The function does not returns anything.
Time Complexity – Linear O(N)
Below program illustrate the above function:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > v(10);
for ( int i = 0; i < 10; i++)
v[i] = i;
cout << "Vector size initially: " << v.size();
cout << "\nVector elements are: ";
for ( int i = 0; i < 10; i++)
cout << v[i] << " ";
v.resize(5);
cout << "\n\nVector size after resize(5): "
<< v.size();
cout << "\nVector elements after resize(5) are: ";
for ( int i = 0; i < 10; i++)
cout << v[i] << " ";
v.shrink_to_fit();
cout << "\n\nVector size after shrink_to_fit(): "
<< v.size();
cout << "\nVector elements after shrink_to_fit() are: ";
for ( int i = 0; i < 10; i++)
cout << v[i] << " ";
return 0;
}
|
Output:
Vector size initially: 10
Vector elements are: 0 1 2 3 4 5 6 7 8 9
Vector size after resize(5): 5
Vector elements after resize(5) are: 0 1 2 3 4 5 6 7 8 9
Vector size after shrink_to_fit(): 5
Vector elements after shrink_to_fit() are: 0 1 2 3 4 0 127889 0 0 0
Last Updated :
31 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...