Multidimensional Arrays and std::mdspan

# Accessing Elements in an mdspan

## How do I access individual elements in a multidimensional span?

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.

This Question is from the Lesson:

### Multidimensional Arrays and std::mdspan

A guide to std::mdspan, allowing us to interact with arrays as if they have multiple dimensions

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

This Question is from the Lesson:

### Multidimensional Arrays and std::mdspan

A guide to std::mdspan, allowing us to interact with arrays as if they have multiple dimensions

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.