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: 6

In 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: 7

Here, 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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Array Initialization
What are the different ways to initialize a std::array in C++?
Passing Arrays by Reference
Why is it more efficient to pass a std::array by reference to a function instead of by value?
Out-of-Bounds Array Access
What happens if I try to access an element in a std::array using an index that is out of bounds?
Changing Array Size
Can I change the size of a std::array after it has been created?
std::array vs C-style Arrays
What are the advantages of using std::array over traditional C-style arrays?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant