C++ Standard Library C++ STL Library

C++ <vector> - shrink_to_fit() Function



The C++ vector::shrink_to_fit function is used to change the vector capacity and makes it equal to the size of the vector. This may cause a reallocation, but there will be no effect on vector size and all elements of the vector will be unaltered.

Syntax

void shrink_to_fit();

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Linear i.e, Θ(n) at most.

Example:

In the example below, the vector::shrink_to_fit function is used to change the vector capacity and makes it equal to the size of the vector MyVector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<string> MyVector (50);

  cout<<"MyVector capacity is: "<<MyVector.capacity();

  MyVector.resize(10);
  cout<<"\nMyVector capacity is: "<<MyVector.capacity();

  MyVector.shrink_to_fit();
  cout<<"\nMyVector capacity is: "<<MyVector.capacity();
  return 0;
}

The output of the above code will be:

MyVector capacity is: 50
MyVector capacity is: 50
MyVector capacity is: 10

❮ C++ <vector> Library