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.

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