mdspan/layoutleft.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 with column-major order layout:
  std::mdspan<int, std::dextents<std::size_t, 3>, std::layout_left>
     mdsL{vec.data(), 2, 5, 3};
  print3D(mdsL);

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

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