In C++, std::array::size() returns the number of elements in the array. For std::array<T, N> the answer is always N.
Unlike a plain C array, a std::array remembers its own size, so you never need sizeof(arr) / sizeof(arr[0]). Include <array> to use it.
This is a member of std::array<T, N>, not of a plain C array and not of std::vector. A std::array has a fixed size N that is part of its type, and it lives on the stack like a normal variable.
Syntax
Call size with empty brackets. It takes no arguments.
C++
std::size_t count = nums.size();
for (std::size_t i = 0; i < nums.size(); ++i) { }
Call
What it does
nums.size()
Returns the number of elements.
i < nums.size()
A common loop condition that keeps the index inside the array.
The result type is std::size_t, which is unsigned. Use it for loop counters to avoid warnings.
Library declarations
C++
constexpr size_type size() const noexcept;
Parameters
Parameter
Description
None
size() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
Size
The number of elements, N, of type size_type.
C++ Examples
Example 1 — Basic size()
Print the size of two arrays with different types.