Multidimensional Arrays and std::mdspan

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 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.

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.