Skip to content
Related Articles

Related Articles

Improve Article
vector shrink_to_fit() function in C++ STL
  • Difficulty Level : Basic
  • Last Updated : 07 Jan, 2019

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:




// 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
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :