#include <string> size_type capacity() const;
The capacity() function returns the number of elements that the string can hold before it will need to allocate more space.
For example, the following code uses two different methods to set the capacity of two vectors. One method passes an argument to the constructor that suggests an initial size, the other method calls the reserve function to achieve a similar goal:
vector<int> v1(10); cout << "The capacity of v1 is " << v1.capacity() << endl; vector<int> v2; v2.reserve(20); cout << "The capacity of v2 is " << v2.capacity() << endl;
When run, the above code produces the following output:
The capacity of v1 is 10 The capacity of v2 is 20
C++ containers are designed to grow in size dynamically. This frees the programmer from having to worry about storing an arbitrary number of elements in a container. However, sometimes the programmer can improve the performance of her program by giving hints to the compiler about the size of the containers that the program will use. These hints come in the form of the reserve() function and the constructor used in the above example, which tell the compiler how large the container is expected to get.
The capacity() function runs in constant time.