What is the vector.capacity() function in C++?
The capacity() function is used to get the memory space that is currently allocated for the vector. This function is available in the <vector> header file.
Parameters
The capacity() function does not accept any parameters.
Return value
The capacity() function returns the size of the currently allocated storage capacity of the vector. This size is expressed in terms of the number of elements that the vector can hold.
Code
Now, let’s look at the code and see how the capacity() function is used:
#include <iostream>#include <vector>using namespace std;int main() {vector<int> vec;cout << "The capacity of an empty vector: " << vec.capacity();vec.push_back(1);cout << "\nUpdated capacity of the vector: " << vec.capacity();vec.push_back(2);vec.push_back(3);cout << "\nUpdated capacity of the vector: " << vec.capacity();return 0;}
Explanation
-
In lines 1 and 2, we import the required packages.
-
In line 6, we create an empty vector.
-
In line 7, we print the capacity of the empty vector, which comes out to be
0. -
In lines 9 and 10, we insert an element to the vector and then print the capacity, which comes out to be
1. -
In lines 12 to 14, we insert two elements to the vector and then print the capacity, which comes out to be
4. This happens because every time we run out of capacity, the vector doubles its capacity. Therefore, if we insert one element when the capacity of the vector is1, the vector will double its size to2. If we insert one more element, the vector will double its size to4.