Static Arrays using std::array

Accessing Elements in Nested Arrays

How do I access elements in a multidimensional std::array?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved