Iterating over an mdspan
What is the best way to iterate over all elements in a multidimensional span?
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 12Using 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 12Both approaches yield the same result, so you can choose the one that suits your needs and preferences.
Multidimensional Arrays and std::mdspan
A guide to std::mdspan, allowing us to interact with arrays as if they have multiple dimensions