C++ Standard Library C++ STL Library

C++ <string> - reserve() Function



The C++ string::reserve function is used to reserve the string capacity be at least enough to contain specified number of characters (n). If n is greater than the current string capacity, then the function increases the string capacity to n (or greater). If n is less than or equal to the string capacity, then string capacity may remain unaffected.

Syntax

void reserve (size_t n);
void reserve (size_t n);

Parameters

n Minimum capacity for the string.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the string::reserve function is used to request a capacity change of the string called MyString.

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string MyString = "AlphaCodingSkills";
 
  cout<<"MyString capacity is: "<<MyString.capacity()<<"\n";
  MyString.reserve(50);
  cout<<"MyString capacity is changed to: "<<MyString.capacity()<<"\n";
  
  return 0;
}

The output of the above code will be:

MyString capacity is: 17
MyString capacity is changed to: 50

❮ C++ <string> Library

5