Lesson content
Read, practise, then check your understanding
A built-in array stores a fixed number of same-type elements contiguously. Indices run from zero to size minus one; out-of-bounds access is undefined behavior. In most expressions a raw array decays to a pointer, losing its extent.
#include <array>
#include <span>
std::array<int, 4> scores{72, 84, 91, 68};
int total(std::span<const int> values) {
int result{};
for (int value : values) result += value;
return result;
}
std::array<T, N> is a regular fixed-size container with .size(), iterators, comparison, and .at() bounds checking. std::vector is better when size changes at runtime. std::span is a non-owning view that passes contiguous data with its size; the viewed storage must outlive the span.
Multiple dimensions
std::array<std::array<int, 3>, 2> matrix{{
{1, 2, 3},
{4, 5, 6}
}};
for (const auto& row : matrix) {
for (int value : row) { /* use value */ }
}
Built-in multidimensional arrays and nested std::array objects use row-major layout: the rightmost dimension is contiguous. A vector-of-vectors supports irregular rows but is not one contiguous matrix. Choose layout based on ownership, size variability, cache access, and interface needs. Prefer range iteration and algorithms; use indices only when position itself is part of the problem.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.