Multidimensional Arrays and std::mdspan

Using mdspan with Algorithms

Can I use mdspan with standard library algorithms?

Abstract art representing computer programming

Yes, you can use std::mdspan with standard library algorithms that operate on contiguous ranges of elements. std::mdspan provides a contiguous view of the underlying memory, which makes it compatible with many standard library algorithms.

To use std::mdspan with algorithms, you can obtain a pointer to the underlying data using the data() member function and pass it along with the size of the mdspan to the algorithm.

Here's an example that demonstrates using std::mdspan with the std::sort algorithm:

#include <algorithm>
#include <iostream>
#include <mdspan>

int main() {
  std::array<int, 6> arr{4, 2, 6, 1, 5, 3};
  std::mdspan<int, std::extents<
    size_t, 2, 3>> span{};

  // Sort the elements in the mdspan
  std::sort(, + span.size());  

  std::cout << "Sorted elements:\n";
  for (size_t i = 0; i < span.extent(0); ++i) {
    for (size_t j = 0; j < span.extent(1); ++j) {
      std::cout << span[i, j] << " ";
    std::cout << "\n";
Sorted elements:
1 2 3
4 5 6

In this example, we create an mdspan object span that provides a 2D view of the underlying array arr.

To sort the elements in the mdspan, we pass as the beginning of the range and + span.size() as the end of the range to the std::sort algorithm. This effectively sorts the elements in the underlying array.

After sorting, we can access the sorted elements through the mdspan using the [i, j] syntax, and they will reflect the sorted order.

It's important to note that when using std::mdspan with algorithms, the algorithms operate on the underlying contiguous memory, not on the multidimensional view itself. The mdspan acts as a wrapper that provides a multidimensional interface to the underlying data.

However, you can still benefit from the convenience and expressiveness of std::mdspan when working with algorithms. You can use mdspan to provide a more intuitive and structured view of the data, while leveraging the performance and flexibility of standard library algorithms.

Keep in mind that if you need to perform operations that are specific to the multidimensional nature of the data, such as matrix multiplication or convolution, you may need to implement those operations separately or use specialized libraries that handle multidimensional data efficiently.

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