Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 171 ยท Arrays and Vectors

std::array

Learn std::array, the zero-cost fixed-size array of modern C++ - creating it, at() vs [], size(), fill, iteration, copying, comparison and passing it to functions.

std::array<T, N> is a fixed-size array wrapped in a tiny struct. It stores exactly the same N elements, in exactly the same memory, as a C-style T[N], so it costs nothing extra. In return it fixes every annoyance of raw arrays from the previous lesson: it knows its size, it doesn't decay to a pointer, = copies it, == compares its contents, functions can return it, and at() checks indexes for you.

Whenever you need a collection whose size is known at compile time, such as the seven days of a week, the RGB channels of a pixel, or the nine cells of a tic-tac-toe board, std::array is the modern default. For collections that grow and shrink, use std::vector, the next lesson.

Creating a std::array

Include <array> and give two template arguments: the element type and the number of elements.

C++
#include <array>

std::array<int, 5> scores{90, 85, 77, 92, 68};   // five ints
std::array<double, 3> rgb{};                     // three zeros
std::array<int, 4> partly{1, 2};                 // {1, 2, 0, 0}
std::array<int, 3> garbage;                      // local: indeterminate values!

The initialization rules are the same as for C arrays: unlisted elements become zero, {} zeroes everything, and a local std::array with no initializer holds indeterminate values. Always use braces.

Since C++17 the compiler can also deduce both arguments from the initializer, and C++20's std::to_array turns a braced list or a C array into a std::array with the size counted for you:

C++
std::array primes{2, 3, 5, 7, 11};               // std::array<int, 5>
auto names = std::to_array({"Ada", "Linus"});    // std::array<const char*, 2>
auto bytes = std::to_array<unsigned char>({0xDE, 0xAD});   // pick the type, count the size

Deduction requires all elements to have the same type; std::array mixed{1, 2.5} is an error.

C++ Creating and inspecting arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

size() is known at compile time and stored nowhere: sizeof(scores) equals sizeof(raw), 20 bytes. std::println prints a whole std::array in brackets (C++23 range formatting), and front() and back() return the first and last elements.

std::array is an aggregate: a plain struct whose only member is a C array. That's why brace initialization works without any constructor, and why you may see old code with double braces, std::array<int, 3> a{{1, 2, 3}}. Since C++14 the single-brace form is always enough.

Accessing elements: [] vs at()

You have four ways to reach elements:

Member What it does On a bad index
a[i] Element i, no checking Undefined behavior
a.at(i) Element i, checked Throws std::out_of_range
a.front() / a.back() First / last element UB for a zero-size array
a.data() Pointer to the first element (for C APIs) n/a

[] is exactly as fast and as dangerous as on a raw array. at() compares the index with size() first and throws an exception if it's out of range. Exceptions get a full lesson in Exceptions; for now, a try block runs code, and a catch block handles the error if one is thrown:

C++ Checked access with at()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Index 9 throws, and the catch prints GCC's message: array::at: __n (which is 9) >= _Nm (which is 4). The exact wording differs between standard libraries, so never parse it; just know that an exception happened.

When should you use which? Use at() when the index comes from outside the program (user input, a file, a network message) and you haven't validated it. Inside a loop like for (std::size_t i = 0; i < a.size(); ++i) the index is correct by construction, so [] is fine. Even better, use a range-based for and avoid indexes altogether.

GCC and Clang can make [] check indexes too, in debug builds. Compile with -D_GLIBCXX_ASSERTIONS (libstdc++) or -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST (libc++), and a bad index aborts the program with a clear message instead of silently corrupting memory. Many projects enable this even in release builds.

Iterating

Every loop style from for Loops and Range-Based for works:

C++
std::array<int, 4> levels{3, 1, 4, 1};

for (int level : levels) { /* read a copy */ }
for (int& level : levels) { level *= 10; }      // modify in place
for (std::size_t i = 0; i < levels.size(); ++i) { /* need the index */ }
for (auto it = levels.begin(); it != levels.end(); ++it) { /* iterators */ }

begin() and end() return iterators, which algorithms use to walk through the elements. std::array works with every standard algorithm, in the classic form (std::sort(a.begin(), a.end())) or the ranges form (std::ranges::sort(a)):

C++ fill, algorithms and iteration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

fill is the clean way to reset an array to one value. The std::string_view(bar.data(), bar.size()) line treats the characters as text without copying them, because data() gives the pointer a C-style function would want. std::ranges::minmax returns both extremes at once, unpacked with a structured binding.

Copying, assigning and comparing

Because std::array is a regular value type, the operators do what you would expect from an int:

  • b = a; copies every element (both must have the same type and size).
  • Passing by value or returning from a function copies the elements too.
  • == and != compare element by element.
  • <, <=, >, >= and <=> compare lexicographically, like words in a dictionary: the first position where the elements differ decides the result. Both sides always have the same size, so there's no "shorter one" case.
C++ Arrays are values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Changing copy doesn't touch installed: they are separate objects. Version [1, 10, 0] is greater than [1, 9, 7] because the comparison stops at the first difference, 10 vs 9. Using a std::array alias for a version number is neat for a demo; in real code a struct with named members (major, minor, patch) is usually clearer, as Structs, Aggregates and Unions shows.

Passing std::array to functions

The size is part of the type, so std::array<int, 3> and std::array<int, 4> are completely different types. That's a feature (sizes can't get lost) and a limitation (a function written for one size rejects the others). You have three options:

C++
// 1. A specific size, read-only, no copy:
double average3(const std::array<double, 3>& values);

// 2. Any size, deduced by a template:
template <std::size_t N>
double average(const std::array<double, N>& values);

// 3. Any contiguous sequence (std::array, std::vector, C array):
double average(std::span<const double> values);

Pass by const& to avoid copying all the elements; passing by value copies the whole array, which is fine for three ints and wasteful for ten thousand. The template version generates one function per size you use. The std::span version, covered in std::span, is often the best choice for a function that just reads a sequence. Parameters explains the by-value vs by-reference choice in depth.

Compile-time arrays

Almost everything about std::array is constexpr, so you can build lookup tables that are computed entirely by the compiler and stored in the program, with no startup cost:

C++ A table computed at compile time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

If you change 49 to 50 in the static_assert, the program no longer compiles. Compile-time programming is explored in Compile-Time Programming; Constants introduces constexpr.

Pitfalls and limits

  • The size can't change. There is no push_back. If you need to add elements, you need a std::vector.
  • It lives where you declare it. A local std::array<double, 1'000'000> puts 8 MB on the stack, which usually overflows it (typical limits are 1 to 8 MB). Large or runtime-sized data belongs in a std::vector, which stores its elements on the heap.
  • Uninitialized locals. std::array<int, 3> a; is just as uninitialized as int a[3];. Write {}.
  • std::array<T, 0> is allowed and size() is 0, but front() and back() on it are undefined behavior.
  • Moving is not cheaper than copying for std::array<int, N>: the elements are inside the object, so moving still copies them one by one. A std::vector can move by handing over a pointer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. std::array<int, 4> a{7}; What does a contain?

    Like a C array, unlisted elements are value-initialized to 0. To set every element to 7, call a.fill(7).
  2. 2. What happens when a.at(5) is called on a std::array<int, 5>?

    at() checks the index against size(). Valid indexes are 0 to 4, so 5 throws std::out_of_range. a[5] would be undefined behavior instead.
  3. 3. std::array<int, 3> x{1, 2, 3}; auto y = x; y[0] = 10; What is x[0]?

    std::array is a value type. auto y = x makes an independent copy, so changing y leaves x untouched.
  4. 4. What does std::array{1, 9, 9} < std::array{2, 0, 0} evaluate to?

    Comparison is lexicographic. The first differing position decides the result, and here that's index 0, where 1 < 2.
  5. 5. Why can't a function taking const std::array<int, 3>& be called with a std::array<int, 4>?

    std::array<int, 3> and std::array<int, 4> are unrelated types. Use a template on N or std::span to accept any size.

Summary

  • std::array<T, N> (from <array>) is a fixed-size array with the same memory layout and speed as T[N].
  • Initialize with braces; {} zeroes it. CTAD (std::array a{1, 2, 3}) and std::to_array deduce the size.
  • [] is unchecked, at() throws std::out_of_range; front(), back(), data() and size() round out access.
  • It copies with =, compares with == and < (lexicographically), can be returned from functions and unpacked with structured bindings.
  • fill sets every element; all standard algorithms and range-based for work on it.
  • The size is part of the type: pass by const&, write a template on N, or take a std::span.
  • It can't grow, and huge ones overflow the stack; use std::vector for dynamic or large data.

Next: std::vector, the dynamic array that grows as you add elements and is the most used container in C++.