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 str.

#include <iostream>
#include <string>

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

The output of the above code will be:

str capacity is: 17
str capacity is changed to: 50

❮ C++ <string> Library