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.
// raw code
#include <iostream>
#include <vector>
#include <ranges>
#include <mdspan>
#include "print3d.hpp"
int main()
{
std::vector vec{std::from_range, std::views::iota(1, 101)}; // elements from 1 to 100
// 2 blocks with offset 2 of 5 rows with offset 12 of 3 columns with offset 4:
std::mdspan mds{vec.data(),
std::layout_stride::mapping{std::extents{2, 5, 3},
std::array{2, 12, 4}}};
// double check that the size fits:
if (mds.mapping().required_span_size() > vec.size()) {
std::cerr << "ERROR: underlying data has not enough elements\n";
return 1;
}
print3D(mds);
}