Length of std::array

Similar to std::vector, we can use same functions to get std::array length. Here also, the returned length value is of type size_type which is always an alias to std::size_t.

If we see, std::array is implemented as a struct template as shown below:

// taken from the source in C++ standard containers library
template<typename _Tp, std::size_t _Nm>
    struct array
    {

Length is a non-type template argument of type std::size_t. std::size_t is explicitly mentioned because typename std::array<T>size_type is not defined at this point (why I have used typename here, read this).

As length is non-type template argument, it always to be a constexpr and thus length of std::array will always be constexpr. Functions which return std::array length can be used in constexpr contexts for example,

std::array<int, 5> items{1, 2, 3, 4, 5};
constexpr int length{items.size()}; // as length is constexpr .size() can be used here.

Other function to get array length:

  1. std::size() which returns size_type length value
  2. std::ssize() returns std::ptrdiff_t that is a long signed integral.

Indexing using operator[] or at()

Similar to std::vector, both methods accept value of type size_type. If a signed type value is provided, compiler would raise narrowing conversion warning.

If a constexpr index is provided, compiler would not raise the warning unless index goes out of range for unsigned type. For example,

constexpr int index{-1};
std::cout << items[index];

index is constexpr but it has negative value, compiler would raise narrow conversion warning.

operator[] does not do bound checking but at() does at runtime and we should avoid using at() because of this overhead.

There is one template function std::get() that indexes element and does compile time bound check.

References

  1. https://www.learncpp.com/cpp-tutorial/stdarray-length-and-indexing/