std::array

std::array in C++

A complete guide to std::array in C++: declaring, initializing, reading elements, looping, passing to functions, and how it compares to C-style arrays.

On this page
  1. What std::array is
  2. Declaring and initializing
  3. Reading and changing elements
  4. Looping over the elements
  5. Passing an std::array to a function
  6. Returning an std::array
  7. std::array compared with C-style arrays
  8. std::array or std::vector
  9. Memory and size limits
  10. Common mistakes
  11. When to use std::array

What std::array is

std::array is a container from the <array> header, added in C++11. It holds a fixed number of elements that all have the same type. The element count is part of the type, so std::array<int, 3> and std::array<int, 5> are different types. Because the size is fixed when the code is compiled, an std::array never grows or shrinks, and it does not allocate memory on the heap.

Declaring and initializing

To declare one, give the element type and the size in angle brackets. The values go in braces after the name.

#include <array>

std::array<int, 5> zeros{};                // all five elements are 0
std::array<int, 5> scores = {90, 75, 88};  // 90, 75, 88, 0, 0
std::array temps{21.5, 19.0, 23.2};        // C++17: deduces std::array<double, 3>

If you give fewer values than the size, the remaining elements are set to zero. If you give more values than the size, the code does not compile.

A local std::array declared without braces, such as std::array<int, 5> numbers;, has indeterminate values for int. Reading those values before you assign them is undefined behavior, so add {} or fill the array first.

The size must be a constant known at compile time. std::array<int, n> does not compile when n is an ordinary variable.

Reading and changing elements

This program shows the most common operations:

#include <array>
#include <iostream>

int main() {
    std::array<int, 4> values{10, 20, 30, 40};

    values[1] = 25;                                             // changes the second element
    std::cout << values.at(1) << '\n';                          // 25
    std::cout << values.size() << '\n';                         // 4
    std::cout << values.front() << ' ' << values.back() << '\n';  // 10 40
}

The output is:

25
4
10 40

There are several ways to reach an element:

  • values[i] is fast, but it does not check the index.
  • values.at(i) checks the index and throws std::out_of_range if the index is outside the array.
  • values.front() and values.back() return the first and last elements.
  • values.size() returns the number of elements as a std::size_t.
  • std::get<2>(values) returns the element at index 2. The index is written in angle brackets, so it must be a constant, and it must be less than the size.

Reading or writing past the end with [] is undefined behavior. The program may print a wrong value or crash. For why a crash can happen this way, see what is segmentation fault in c.

Looping over the elements

A range-based for loop is the simplest way to visit every element:

#include <array>
#include <iostream>

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

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

Use const auto& instead of int when each element is costly to copy, such as a std::string, so the loop does not copy every element.

Standard algorithms work on an std::array too. For example, std::sort from <algorithm> sorts the elements in place when you pass begin() and end().

Passing an std::array to a function

Because the size is part of the type, a parameter of type std::array<int, 4> accepts only arrays of four int values. To accept any size, use a template parameter for the size:

#include <array>
#include <cstddef>
#include <iostream>

template <std::size_t N>
void printAll(const std::array<int, N>& items) {
    for (int item : items) {
        std::cout << item << ' ';
    }
    std::cout << '\n';
}

Passing by const reference avoids copying the elements. The const also tells readers that the function will not change them. For more on what const does, see c const keyword.

A C-style array loses its size when it is passed to a function, so the function usually needs the size as a separate argument. For that case, see how to pass an array to a function in c.

Returning an std::array

An std::array can be returned by value, so the caller receives a full copy of the elements:

#include <array>

std::array<int, 3> makeRange() {
    return {1, 2, 3};
}

A C-style array cannot be returned this way. For the C-style options, see how to return an array in c.

std::array compared with C-style arrays

A C-style array such as int numbers[5]; is also fixed in size, but it behaves differently in a few ways:

  • Size: an std::array reports its own size with size(). A C-style array does not, so you have to use sizeof, and that only works where the array is declared.
  • Copying: = copies every element of an std::array. A C-style array cannot be assigned with =.
  • Bounds checking: at() checks the index for an std::array. C-style arrays have no equivalent.
  • Function arguments: an std::array is passed as one object. A C-style array turns into a pointer when it is passed to a function.
  • C interfaces: C-style arrays are still needed when a C library expects one. An std::array gives you a pointer to its elements through data().

std::array or std::vector

Choose std::array when the number of elements is fixed. A std::vector is the better fit when the count changes while the program runs. A vector stores its elements on the heap and can grow with push_back, but an std::array has neither. For how to set one up, read c vector initialization.

Memory and size limits

An std::array stores its elements inside the object itself. A local std::array lives wherever its variable lives, which is usually the stack. The stack has a limited size, so a very large local std::array can overflow it and crash the program. For large amounts of data, use a std::vector, or declare the array as static or at namespace scope. For how the stack and the heap differ, see c heap vs stack.

Common mistakes

  • Using an ordinary variable as the size, such as std::array<int, n>. The size must be a constant.
  • Indexing past the end. The valid indexes run from 0 to size() - 1.
  • Expecting an std::array to grow. Its size never changes.
  • Forgetting #include <array>.

When to use std::array

Use std::array when the number of values is fixed and known when you write the code, such as three color channels or the four corners of a rectangle. It keeps its size with the data and can be copied and passed around like any other value. C-style arrays still appear in older code and in C libraries, so it helps to recognize them too.

Keep exploring

Guides from other topics

All topics →

Is C++ Harder Than Python?

For most beginners, C++ is harder than Python because it needs a compiler, explicit types and careful memory handling. See why, with a side-by-side example.

C++ vs Python 4 min read