.capacity()
In C++, the .capacity()
method returns the amount of storage currently allocated for the string. This capacity is always equal to or greater than the value returned by the .size()
method. The .capacity()
method is useful for optimizing performance in scenarios where a string undergoes frequent modifications. It helps determine how much memory is already allocated, which can reduce unnecessary reallocations during operations such as appending in loops or constructing large strings. When used alongside .reserve()
, it enables preallocation of sufficient space, enhancing efficiency in performance-critical applications.
Syntax
string.capacity();
Parameters:
- The
.capacity()
method does not take any parameters.
Return value:
Returns a size_t
value representing the number of characters the string can hold without requiring a reallocation of memory.
Example
This example demonstrates the basic usage of the .capacity()
method and how it can differ from the .size()
of the string:
#include <iostream>#include <string>using namespace std;int main() {string message = "Hello";cout << "String: " << message << '\n';cout << "Size: " << message.size() << '\n';cout << "Capacity: " << message.capacity() << '\n';return 0;}
The output of the code above will be:
String: HelloSize: 5Capacity: 15
Codebyte Example
This codebyte example shows how the .capacity()
of a string can grow when needed, and how it may stay the same when there’s already enough reserved space:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours