11.5. The std::array classΒΆ

The std::array is a container that encapsulates fixed size arrays. Since it is literally a wrapper around a raw array, the size of a std::array must be defined when declared.

std::array <int, 12> days_per_month;

The array class is very lightweight and has very little costs over a raw array. Additionally, std::array provides convenience functions such as:

at() and operator[]

range checked access and unchecked access

front() and back()

access to the first and last elements

size()

return the number of elements

empty()

check if the container is empty

Unlike a raw array, std::array cannot infer its size if declared with an initializer list:

 1#include <array>
 2#include <iostream>
 3using std::cout;
 4
 5int main() {
 6  // compile error: array template parameter missing:
 7  //std::array<char> letters = {{'h', 'o', 'w', 'd', 'y', '!'}};
 8
 9  std::array<char, 6> letters = {{'h', 'o', 'w', 'd', 'y', '!'}};
10
11  cout << "The first character is: " << letters.front() << '\n';
12  cout << "The last character is: " << letters.back() << '\n';
13
14  for (const auto& c: letters) {
15    cout << c;
16  }
17}

More to Explore