![]() |
VOOZH | about |
In C++, the vector capacity() is a built-in method used to find the capacity of vector. The capacity indicates how many elements the vector can hold before it needs to reallocate additional memory. In this article, we will learn about vector capacity() method in C++.
Let’s take a look at an example that illustrates vector capacity() method:
5
This article covers the syntax, usage, and common usage of vector capacity() method in C++:
Table of Content
The vector capacity() is the member method of std::vector class defined inside <vector> header file.
v.capacity();
The following examples demonstrates the use vector capacity() function for different purposes:
5 10
Explanation: Initially the capacity of vector is 5, but on adding new elements in vector if the size exceeded current capacity, then capacity increase by double of previous capacity. So, the new capacity become 10 because previous capacity was 5.
5
Explanation: The capacity of vector will not decrease automatically on removing the elements from vector.
3
Explanation: Initially the capacity of vector is 5 but on removing 2 elements from vector, the capacity is still 5. So we use vector shrink_to_fit() method to decrease the capacity of vector which makes the capacity will equal to size of vector.