C++ <string> - capacity() Function
The C++ string::capacity function returns size of currently allocated space to the string, expressed in terms of characters. The returned value is not necessarily equal to the string length. It can be greater than or equal to as compared to the string length, with the extra space required for the string object to optimize its operations.
Syntax
size_type capacity() const;
size_type capacity() const noexcept;
Parameters
No parameter is required.
Return Type
Returns size of currently allocated space to the string, measured in terms of number of characters it can hold.
Example:
In the example below, the string::capacity function is used find out the size of currently allocated space to the string str.
#include <iostream> #include <string> using namespace std; int main (){ string str = "Hello World!."; cout<<"The String is: "<<str<<"\n"; cout<<"String length: "<<str.length()<<"\n"; cout<<"String size: "<<str.size()<<"\n"; cout<<"String capacity: "<<str.capacity()<<"\n"; return 0; }
A possible output could be:
The output of the above code will be:
The String is: Hello World!. String length: 13 String size: 13 String capacity: 15
❮ C++ <string> Library