String Shrink To Fit Function - C++ Programming Tutorial
C++ Course / Strings / String Shrink To Fit Function

String Shrink To Fit Function

BLUF: Mastering String Shrink To Fit Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: String Shrink To Fit Function

C++ is renowned for its efficiency. Learn how String Shrink To Fit Function enables low-level control and high-performance computing in the tutorial below.

This function decreases the string's capacity to match its size.

Syntax

Consider a string str. Synatx would be:

Example

str.shrink_to_fit();

Parameter

It does not contain any parameter.

Return value

It does not return any value.

Example 1

Let's see the simple example.

Example

#include<iostream>
using namespace std;
int main()
{
	string str="C++ Programming";
	cout<<str.capacity()<<'\n';
	str.shrink_to_fit();
	cout<<str.capacity();
	return 0;
}

Output:

In this instance, the shrinktofit method is utilized on the string to adjust the capacity of the string to match its size.

Example 2

Let's see another simple example.

Example

#include<iostream>
using namespace std;
int main()
{
	string str="Computer is my favorite subject";
	cout<<"Initial string value is :"<<str<<'\n';
	str.resize(24);
	cout<<"After resizing,string value is :"<<str<<'\n';
	str.shrink_to_fit();
	cout<<"capacity of the string is :"<<str.capacity()<<'\n';
	cout<<"size of the string is  :"<<str.size();
            return 0;
}

Output:

Output

Initial string value is: Computer is my favorite subject
After resizing, string value is: Computer is my favorite 
capacity of the string is :24
size of the string is  :24

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience