std::array

What Is std::array in C++?

std::array is a container from the <array> header, added in C++11. It stores a fixed number of same-typed elements, shown in a short example.

On this page
  1. The short answer
  2. A simple example
  3. What makes it different
  4. How it compares with a C-style array
  5. When to use it

The short answer

std::array is a fixed-size container from the <array> header, added in C++11. It holds a set number of elements of one type. Its size is set when the code is compiled and cannot change while the program runs.

A simple example

#include <array>
#include <iostream>

int main() {
    std::array<int, 3> lengths{4, 8, 15};

    for (int length : lengths) {
        std::cout << length << '\n';
    }

    std::cout << "Count: " << lengths.size() << '\n';
}

The output is:

4
8
15
Count: 3

The angle brackets hold two things: the element type, int, and the number of elements, 3.

What makes it different

  • Fixed size: the number of elements is part of the type, and size() returns it.
  • Storage: the elements are stored inside the object, so std::array does not allocate memory on the heap.
  • Copying: = copies every element.
  • Loops and algorithms: it works with range-based for loops and with standard algorithms such as std::sort.
  • Checked access: at() throws an exception if the index is out of range. [] does not check.

How it compares with a C-style array

A C-style array such as int lengths[3] also has a fixed size, but it does not know its own size, cannot be copied with =, and turns into a pointer when you pass it to a function. std::array avoids those problems, which is one reason it is often preferred in modern C++.

When to use it

Use std::array when you know the number of elements in advance, such as three color channels or the four corners of a rectangle. If the count changes while the program runs, use std::vector instead. For a longer walkthrough with more examples, read c std::array.

The complete guide to std::array

std::array in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Unary Operators in C++

Learn what unary operators in C++ are, from the one-operand symbols like !, ~, ++ and * to prefix vs postfix, precedence and common mistakes, with examples.