10.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:

#include <array>
#include <iostream>
using std::cout;

int main() {
  // compile error: array template parameter missing:
  //std::array<char> letters = {{'h', 'o', 'w', 'd', 'y', '!'}};

  std::array<char, 6> letters = {{'h', 'o', 'w', 'd', 'y', '!'}};

  if (!letters.empty()) {
    cout << "The first character is: " << letters.front() << '\n';
    cout << "The last character is: " << letters.back() << '\n';

    for (const auto& c: letters) {
      cout << c;
    }
    cout << std::endl;
  }
}

More to Explore

You have attempted of activities on this page