C++ String Library - shrink_to_fit


Advertisements


Description

It requests the string to reduce its capacity to fit its size.

Declaration

Following is the declaration for std::string::shrink_to_fit.

void shrink_to_fit();

C++11

void shrink_to_fit();

Parameters

none

Return Value

none

Exceptions

if an exception is thrown, there are no changes in the string.

Example

In below example for std::string::shrink_to_fit.

Live Demo
#include <iostream>
#include <string>

int main () {
   std::string str (500,'x');
   std::cout << "1. capacity of str: " << str.capacity() << '\n';

   str.resize(10);
   std::cout << "2. capacity of str: " << str.capacity() << '\n';

   str.shrink_to_fit();
   std::cout << "3. capacity of str: " << str.capacity() << '\n';

   return 0;
}

The sample output should be like this −

1. capacity of str: 500
2. capacity of str: 500
3. capacity of str: 10

string.htm

Advertisements