Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


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 below example, the string::shrink_to_fit function is used to change the string capacity and makes it equal to the size of the string MyString.

#include <iostream>
#include <string>
using namespace std;
 
int main (){
  string MyString (50, 'x');

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

  MyString.resize(10);
  cout<<"\nMyString capacity is: "<<MyString.capacity();

  MyString.shrink_to_fit();
  cout<<"\nMyString capacity is: "<<MyString.capacity();
  return 0;
}

The output of the above code will be:

MyString capacity is: 50
MyString capacity is: 50
MyString capacity is: 10 

❮ C++ - String Functions