Accessing Elements in Nested Arrays
How do I access elements in a multidimensional std::array?
To access elements in a multidimensional std::array, you use multiple sets of square brackets [], one for each dimension.
Here's an example of a 2D array (an array of arrays):
#include <array>
#include <iostream>
int main() {
  std::array<std::array<int, 3>, 2> MyArray{
    {
      {1, 2, 3},
      {4, 5, 6}
    }
  };
  std::cout << "Bottom Right: " << MyArray[1][2];  
}Bottom Right: 6In this case, MyArray is an array that contains 2 elements, each of which is an array of 3 integers.
To access an element, the first set of [] specifies which sub-array you want, and the second set specifies the element within that sub-array. So, MyArray[1][2] accesses the 3rd element (remember, indices start at 0) of the 2nd sub-array, which is 6.
The same principle extends to higher dimensions. For example, the following is a three dimensional array (2x2x2):
#include <array>
#include <iostream>
int main() {
  std::array MyArray{
    std::array{
      std::array{1, 2},
      std::array{3, 4}
    },
    std::array{
      std::array{5, 6},
      std::array{7, 8}
    },
  };
  std::cout << "Value: " << MyArray[1][1][0];  
}Value: 7Here, MyArray[1][1][0] would access the 1st element of the 2nd sub-array of the 2nd sub-array of MyArray, which is 7.
Remember that each set of [] can be an expression that evaluates to an integer, not just a literal integer. For example:
int i = 1;
int j = 2;
int value = MyArray[i][j];This would access MyArray[1][2] just like in the first example.
Also note that each access (MyArray[i][j]) returns a reference to the element, which you can read from or write to.
Static Arrays using std::array
An introduction to static arrays using std::array - an object that can store a collection of other objects