Lesson 88 +10 XP

std::array

std::array

Sometimes you want a fixed-size array with all the safe conveniences of a library container. Enter std::array.

Declaring it

#include <array>

std::array<int, 3> a {10, 20, 30};
  • The template takes two things: the type and the size, std::array<int, 3>.
  • The size is fixed at compile time, like a built-in array.

Reading elements its way

a[0]      // 10  -  fast access, unchecked
a.at(1)   // 20  -  checked access, throws if out of range
a.size()  // 3  -  it knows its own length
  • .size() returns the element count - no sizeof trick needed.
  • .at(i) checks the index and throws an exception if it's out of bounds.
  • [] is unchecked, exactly like a C-style index.

Why prefer over C arrays?

  • It doesn't decay to a pointer when passed to a function.
  • It keeps its size and works with std::size, ranges, and at().
  • Same memory and speed as a built-in array - it's basically a fixed array with safety ribbons.

TL;DR

  • std::array<int, 3> a {10, 20, 30}; - fixed size decided at compile time.
  • Needs #include <array>.
  • .size() knows the length; .at(i) does index-checked access.
  • [] is fast but unchecked; at() is the safe option.
  • Use std::array for fixed-sized arrays, std::vector for growing ones.