Multidimensional Arrays and std::mdspan

Iterating over an mdspan

What is the best way to iterate over all elements in a multidimensional span?

Abstract art representing computer programming

There are a few ways to iterate over all elements in a multidimensional span (std::mdspan). Here are a couple of common approaches:

Using Nested Loops

You can use nested loops to iterate over each dimension of the mdspan. The number of loops required will match the rank (number of dimensions) of the mdspan.In this example, we use two nested loops to iterate over a 2D mdspan.

The outer loop iterates over the rows using matrix.extent(0), and the inner loop iterates over the columns using matrix.extent(1).

#include <iostream>
#include <mdspan>

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

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

  // Iterating using nested loops
  for (size_t i = 0; i < M.extent(0); ++i) {
    for (size_t j = 0; j < M.extent(1); ++j) {
      std::cout << M[i, j] << " ";  
    }
    std::cout << "\n";
  }
}
1 2 3 4
5 6 7 8
9 10 11 12

Using a Single Loop with Arithmetic

Alternatively, you can use a single loop to iterate over all elements by treating the mdspan as a flattened 1D array and using arithmetic to calculate the corresponding indices.In this approach, we use a single loop that iterates from 0 to matrix.size() - 1.

Inside the loop, we calculate the corresponding row and column indices using integer division and modulo operations.

#include <iostream>
#include <mdspan>

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

  // Iterating using a single loop with arithmetic
  for (size_t i = 0; i < matrix.size(); ++i) {
    size_t row = i / matrix.extent(1);  
    size_t col = i % matrix.extent(1);  
    std::cout << matrix[row, col] << " ";
  }
}
1 2 3 4 5 6 7 8 9 10 11 12

Both approaches yield the same result, so you can choose the one that suits your needs and preferences.

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