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.

Multidimensional Arrays and std::mdspan

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

Questions & Answers

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

Iterating over an mdspan
What is the best way to iterate over all elements in a multidimensional span?
Performance Benefits of mdspan
What are the performance benefits of using mdspan compared to nested vectors or arrays?
Layout Mapping in mdspan
What is the purpose of the layout mapping policy in mdspan?
Accessor Policy in mdspan
What is the purpose of the accessor policy in mdspan?
Using mdspan with Algorithms
Can I use mdspan with standard library algorithms?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant