std::array is a fixed-sized array whose length has to be specified while creating it. Unlike std::vector, std::array size can’t be changed once defined which makes it advantageous over vector for certain cases:

  1. std::array is efficient is more performant than vector as there is no reallocation happens (look resizing vectors).
  2. std::array supports constexpr whereas std::vector doesn’t.

Creating and initializing std::array

We need to provide length while defining std::array and length has to be a constexpr. std::array uses aggregate initialization to initialize the array because it is an aggregate datatype. For example:

std::array<int, 5> lists{1, 2, 3, 4, 5};

int is the type template argument (explain in function templates) and 5 is a non-type template argument.

We can also use CTAD to omit template types as shown below:

std::array lists{1, 2, 3, 4, 5};

Accessing elements

Similar to std::vector, we can access std::array elements using operator[] as shown below:

std::cout << lists[0]; // accesses first element

References

  1. https://www.learncpp.com/cpp-tutorial/introduction-to-stdarray/