mdspan/layoutright.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 <print>
#include <vector>
#include <ranges>
#include <mdspan>
#include "print3d.hpp"

int main()
{
  std::vector vec{std::from_range, std::views::iota(1, 81)};  // vector with 1 to 80

  // mdspan of 2 * 5 * 3 elements:
  std::mdspan mds{vec.data(), 2, 5, 3};
  print3D(mds);

  // mdspan of 2 * 5 * 3 elements with row-major order layout:
  std::mdspan<int, std::dextents<std::size_t, 3>, std::layout_right>
     mdsR{vec.data(), 2, 5, 3};
  static_assert(std::same_as<decltype(mds), decltype(mdsR)>);

  // define the mapping:
  std::layout_right::mapping mapR3D{std::extents{2, 5, 3}};
  std::println("required_span_size(): {}", mapR3D.required_span_size());

  // and initialize an mdspan with it:
  std::mdspan mds2{vec.data(), mapR3D};
  static_assert(std::same_as<decltype(mds), decltype(mds2)>);    
  std::println("size:                 {}", mds.size());
  std::println("same mapping:         {}", mds.mapping() == mapR3D);
}