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.


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


n Minimum capacity for the string.

Return Value


Time Complexity

Constant i.e, Θ(1).


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";
  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