C++ Standard Library C++ STL Library

C++ <string> - shrink_to_fit() Function



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

Syntax

void shrink_to_fit();

Parameters

No parameter is required.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

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

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string MyStr (50, 'x');

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

  MyStr.resize(10);
  cout<<"\nMyStr capacity is: "<<MyStr.capacity();

  MyStr.shrink_to_fit();
  cout<<"\nMyStr capacity is: "<<MyStr.capacity();
  return 0;
}

The output of the above code will be:

MyStr capacity is: 50
MyStr capacity is: 50
MyStr capacity is: 10 

❮ C++ <string> Library