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.

Below program illustrate the above function:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


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


My Personal Notes arrow_drop_up

Contented with little yet wishing for more

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : AdityaKumawat1



Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.