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::arraydoes not allocate memory on the heap. - Copying:
=copies every element. - Loops and algorithms: it works with range-based
forloops and with standard algorithms such asstd::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.