Using std::mdspan for multi-dimensional views of sequences of objects
In the previous recipe, Using std::span for contiguous sequences of objects, we learned about the C++20 class called std::span
, which represents a view (a non-owning wrapper) over a contiguous sequence of elements. This is similar to the C++17 std::string_view
class, which does the same but for a sequence of characters. Both of these are views of one-dimensional sequences. However, sometimes we need to work with multi-dimensional sequences. These could be implemented in many ways, such as C-like arrays (int[2][3][4]
), pointer-of-pointers (int**
or int***
), arrays of arrays (or vectors of vectors, such as vector<vector<vector<int>>>
). A different approach is to use a one-dimensional sequence of objects but define operations that present it as a logical multi-dimensional sequence. This is what the C++23 std::mdspan
class does: it represents a non-owning view of a contiguous sequence of objects presented...