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
// C++ program to illustrate // the vector::shrink_to_fit() #include <bits/stdc++.h> using namespace std;
int main()
{ // Initialized vector
vector< int > v(10);
for ( int i = 0; i < 10; i++)
v[i] = i;
// Initial vector
cout << "Vector size initially: " << v.size();
cout << "\nVector elements are: ";
for ( int i = 0; i < 10; i++)
cout << v[i] << " ";
// changes the size of the Vector
// but does not destroys the elements
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] << " ";
// Shrinks to the size
// till which elements are
// destroys the elements after 5
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