#include <vector> size_type capacity() const;
capacity method returns the number of elements that the vector 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 initializes the vector with 10 elements of value 0, and the other method calls the reserve method. However, the actual size of the vector remains zero.
vector<int> v1(10); cout << "The capacity of v1 is " << v1.capacity() << endl; cout << "The size of v1 is " << v1.size() << endl; vector<int> v2; v2.reserve(20); cout << "The capacity of v2 is " << v2.capacity() << endl; cout << "The size of v2 is " << v2.size() << endl;
When run, the above code produces the following output:
The capacity of v1 is 10 The size of v1 is 10 The capacity of v2 is 20 The size of v2 is 0
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 their 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 method and the constructor used in the above example, which tell the compiler how large the container is expected to get.
capacity method runs in constant time.