string shrink_to_fit() function in C++ STL
Last Updated :
27 Jan, 2023
The C++ Standard Template Library (STL) provides a variety of useful classes and functions for working with data structures, including the std::string class for manipulating strings. One of the features of the std::string class is the shrink_to_fit() function, which allows developers to reduce the amount of memory allocated for a string to the minimal amount needed to store its current contents.
When working with strings in C++, it is important to keep in mind that the std::string class is designed to be a dynamically resizable string. This means that the class may allocate more memory than is actually needed to store the string’s contents. The shrink_to_fit() function allows developers to reduce the amount of memory allocated for a string to the minimal amount needed to store its current contents. This can be useful in situations where memory usage is a concern, such as in resource-constrained environments or when working with large amounts of data.
It is important to note that shrink_to_fit() doesn’t guarantee that capacity will be reduced, it just request the reduction, but the implementation is free to ignore it.
Also, it’s worth noting that this function does not change the size of the string, only the capacity. The size will continue to reflect the number of characters in the string, while the capacity will be the amount of memory allocated for the string.
I recommend using namespace std; directive in C++ can be considered bad practice because it can lead to naming conflicts and make the code harder to read and understand.
Syntax:
s.shrink_to_fit();
Parameters: This function does not accept any parameters.
Return value: This function does not return anything.
The shrink_to_fit() function can be called on a string object using the dot notation. For example, the following code demonstrates how to use the shrink_to_fit() function to reduce the amount of memory allocated for a string:
Example :
C++
#include <iostream>
#include <string>
int main()
{
std::string str = "geeksforgeeks is best" ;
std::cout << "String is: " << str << "\n" ;
std::cout << "Size of the string is :" << str.length()
<< "\n" ;
str.resize(13);
std::cout << "After resizing string is: " << str << "\n" ;
std::cout << "Capacity of the string is :" << str.capacity()
<< "\n" ;
str.shrink_to_fit();
std::cout << "New size of the string is :" << str.length()
<< "\n" ;
std::cout << "New capacity of the string is :"
<< str.capacity() << "\n" ;
}
|
Output
String is: geeksforgeeks is best
Size of the string is :21
After resizing string is: geeksforgeeks
Capacity of the string is :21
New size of the string is :13
New capacity of the string is :13
Time complexity: O(N), N is length of string.
Auxiliary space: O(N), because string is immutable.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...