lib/mdspan2d.cpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <iostream>
#include <array>
#include <mdspan>

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

  // use arr as 3 rows of 4 values:
  std::mdspan mds{arr.data(), 3, 4};

  // print the 2-dimensional mdspan:
  for (std::size_t i = 0; i != mds.extent(0); ++i) {
    for (std::size_t j = 0; j != mds.extent(1); ++j) {
      std::cout << mds[i, j] << ' ';
    }
    std::cout << '\n';
  }
}