![]() |
VOOZH | about |
In C++, the vector size() is a built-in method used to find the size of a vector. The size of a vector tells us the number of elements currently present in the vector. In this article, we will learn about the vector size() method.
Let's take a look at the simple code example:
5
Explanation: The number of elements in the vector v is 5, which is returned by the vector size() function.
The vector size() method is the member function of std::vector defined inside <vector> header file.
v.size();
This function does not take any parameters.
Return Value
The vector size() is a very simple and easy to use function. The code examples below show how to use this function:
2 5
The size() method can be used to check whether a vector is empty by comparing its size to zero.
Empty.
1 2 3 5 4
The vector size() returns the number of elements currently stored in the vector while vector capacity() returns the total number of elements the vector can hold before needing to reallocate memory.
| Feature | size() | capacity() |
|---|---|---|
| Purpose | Returns the number of elements in the vector. | Returns the total memory capacity allocated to the vector. |
| Dynamic Behaviour | Increases when elements are added. Decreases when the element is deleted. | May remain the same until a reallocation occurs. |
| Relation | The vector size is always less than or equal to the vector capacity. | Vector capacity is always greater than or equal to the vector size. |