Syntax:
#include <vector> size_type capacity() const;
The capacity() function 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, the other method calls the reserve function. 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 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.