In C++, std::vector::size() returns the number of elements that a std::vector holds right now. A vector with three elements has the size 3.
The size changes whenever you add or remove elements, for example with push_back() or pop_back(). Include <vector> to use it.
This is a member of std::vector<T>, a dynamic contiguous array. Elements sit in one block, so v[i] and data() are fast. Growing past capacity() reallocates and can invalidate iterators, references, and pointers. Prefer push_back / pop_back at the end; middle inserts shift elements.
Syntax
Call size with empty brackets. It takes no arguments.
C++
std::size_t n = v.size();
for (std::size_t i = 0; i < v.size(); ++i) { }
Call
What it does
v.size()
Returns the number of elements.
v.size() - 1
The index of the last element. Careful: it is wrong when the vector is empty.
To only check for no elements, empty() is clearer than size() == 0.
Library declarations
C++
size_type size() const noexcept;
Parameters
Parameter
Description
None
size() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
size_type
An unsigned number: how many elements the vector holds. It is 0 for an empty vector.