15.7. Fixed-size sequences with std::arrayΒΆ
std::array is declared in <array>. Its element type and size are both
part of its type: std::array<int, 3> and std::array<int, 4> are different
types. Use it when the number of elements is known at compile time.
1#include <array>
2#include <iostream>
3
4int main() {
5 std::array<int, 4> readings{18, 21, 19, 22};
6 int total = 0;
7 for (int reading : readings) {
8 total += reading;
9 }
10 std::cout << readings.size() << " readings, total " << total << '\n';
11 readings.at(0) = 20;
12 std::cout << readings.front() << '\n';
13}
List initialization supplies the elements in order. std::array<int, 4> a{};
initializes all four integers to zero. In contrast, a local declaration
std::array<int, 4> a; does not initialize those integers; do not read them
before assigning values.
size() returns an unsigned size type. If you need a position, use
std::size_t from <cstddef>; if you only need the elements, prefer a
range-based for loop. at() checks its index and throws
std::out_of_range if it is invalid. operator[] does not perform this
check in C++20. Neither front() nor back() may be used on an empty array.
An array owns its elements and can be copied or assigned. Its size never
changes: it has no push_back or resize member. A built-in C array lacks
many of these conveniences, so we use std::array for fixed-size sequences.
Nested arrays can describe a rectangular table. The outer array contains
rows; each row contains columns. Access table[row][column], using two
pairs of brackets, not table[row, column].
1#include <array>
2#include <iostream>
3
4int main() {
5 std::array<std::array<int, 3>, 2> table{{{1, 2, 3}, {4, 5, 6}}};
6 for (const auto& row : table) {
7 for (int value : row) {
8 std::cout << value << ' ';
9 }
10 std::cout << '\n';
11 }
12 std::cout << table.at(1).at(2) << '\n';
13}
The dimensions here are two rows and three columns. Each at() checks one
dimension. The elements in an array of arrays have fixed rectangular shape.
We want to open a file and parse its data into our program. What library do we need to include?
In table[9][17], the row index is and the column index is .