Multidimensional Arrays and std::mdspan

Accessing Elements in an mdspan

How do I access individual elements in a multidimensional span?

Abstract art representing computer programming

To access individual elements in a multidimensional span (std::mdspan), you can use the [] operator with multiple indices, one for each dimension.

For example, let's say we have a 2D mdspan called matrix with dimensions 3x4. Here's how we can access its elements:

#include <mdspan>
#include <iostream>

int main() {
  std::array<int, 12> arr{
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

  std::mdspan<int, std::extents<
    std::size_t, 3, 4>> matrix{arr.data()};

  // Accessing elements
  std::cout << "Element at (0, 0): "
    << matrix[0, 0] << "\n";
  std::cout << "Element at (1, 2): "
    << matrix[1, 2] << "\n";
  std::cout << "Element at (2, 3): "
    << matrix[2, 3] << "\n";
}
Element at (0, 0): 1
Element at (1, 2): 7
Element at (2, 3): 12

The first index represents the row, and the second index represents the column. So, matrix[0, 0] accesses the element at the first row and first column, matrix[1, 2] accesses the element at the second row and third column, and so on.

Remember that the indices start at 0 for each dimension. Also, make sure to provide the correct number of indices matching the rank (number of dimensions) of the mdspan.

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:

  • 125 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