In C++23, how does std::mdspan view a flat image buffer as rows and columns, and what do its extents and layout policy decide?
answer
- a span with more dimensions
- extents: rank and sizes
- layout maps indices to offset
- row-major is the default
basics
~20 sstd::mdspan is a C++23 non-owning view that maps multidimensional indices onto a flat buffer. Its extents give the rank and each dimension's size, static or dynamic; its layout policy, layout_right by default, computes the offset for img[r, c].
solid answer
~40 s`std::mdspan<T, Extents, LayoutPolicy, AccessorPolicy>` wraps a pointer to contiguous data and lets you index it as `img[r, c]`, using C++23's multidimensional subscript. **Extents** fix the rank and each dimension's size: `std::extents<std::size_t, 2, 3>` is fully static, `std::dextents<std::size_t, 2>` fully dynamic. The **layout policy** is the mapping from indices to an offset: `std::layout_right`, the default, is row-major (`r * cols + c`); `std::layout_left` is column-major (`r + c * rows`); `std::layout_stride` allows arbitrary strides, such as a sub-image with a row pitch. Changing the layout changes only the arithmetic, not the data. Like `std::span`, mdspan owns nothing, so the buffer must outlive it, and indexing is unchecked. The C++26 draft adds `submdspan`, padded layouts and a checked `at()`.
code
cpp · 24 lines#include <cstdio>
#include <mdspan>
#include <vector>
int main() {
const std::size_t rows = 2, cols = 3;
std::vector<float> rowbuf{0, 1, 2, // stored row by row
3, 4, 5};
std::vector<float> colbuf{0, 3, // the same image, column by column
1, 4,
2, 5};
// Default layout_right: (r, c) is at offset r * cols + c.
std::mdspan a(rowbuf.data(), rows, cols);
// layout_left: (r, c) is at offset r + c * rows.
std::mdspan<float, std::dextents<std::size_t, 2>, std::layout_left> b(colbuf.data(), rows, cols);
std::printf("%g %g\n", a[1, 2], b[1, 2]); // C++23 subscript: both print 5
std::printf("%zu %zu\n", a.stride(0), b.stride(0)); // 3 and 1
// A fixed 2x3 tile: both extents are part of the type.
std::mdspan<float, std::extents<std::size_t, 2, 3>> tile(rowbuf.data());
std::printf("%zu %zu\n", tile.extent(1), a.extent(1));
}go deeper
Recall that std::mdspan is a C++23 non-owning view that indexes a flat buffer with several indices, such as img[r, c].
Explain extents (rank, static or dynamic sizes) and the default layout_right mapping r * cols + c, and how layout_left changes only the offset formula.
Choose the layout that matches the data's producer, use layout_stride for sub-images or transposed views, and keep the owning buffer's lifetime longer than every mdspan over it.
Decide whether a codebase replaces hand-written index arithmetic and in-house matrix views with std::mdspan, given C++23 availability and that submdspan arrives only with C++26.
## The problem mdspan solves Images, matrices and tensors are usually stored as one flat, contiguous buffer, because that is what allocators, file formats, GPUs and C libraries hand you. Code then indexes it by hand: `pixels[r * cols + c]`. The formula is repeated everywhere, it hard-codes row-major order, and a mix-up between `rows` and `cols` compiles cleanly. `std::mdspan` (header `<mdspan>`, C++23) is a **non-owning multidimensional view** over such a buffer. Like `std::span`, it holds a pointer and some sizes, owns nothing, and must not outlive the buffer. Unlike span, it maps a tuple of indices to an offset for you. ## The four template parameters ```cpp template<class ElementType, class Extents, class LayoutPolicy = layout_right, class AccessorPolicy = default_accessor<ElementType>> class mdspan; ``` 1. **`ElementType`**: the element type, for example `float`. 2. **`Extents`**: the number of dimensions (the **rank**) and the size of each. `std::extents<std::size_t, 2, 3>` fixes both sizes at compile time; `std::dextents<std::size_t, 2>` makes both dynamic; mixing is allowed with `std::dynamic_extent`, as in `std::extents<std::size_t, std::dynamic_extent, 3>`. 3. **`LayoutPolicy`**: the **mapping** from indices to an offset in the buffer. 4. **`AccessorPolicy`**: how an offset becomes a reference; `default_accessor` simply returns `p[offset]`. Class template argument deduction handles the common case: `std::mdspan img(pixels.data(), rows, cols)` deduces a rank-2 view with dynamic extents and `layout_right`. ## Layouts: the same pixel, different offsets | layout | offset of `(r, c)` in a 2D view | also known as | |---|---|---| | `std::layout_right` (default) | `r * cols + c` | row-major | | `std::layout_left` | `r + c * rows` | column-major | | `std::layout_stride` | `r * stride(0) + c * stride(1)` | arbitrary strides | `layout_right` makes the rightmost index vary fastest, matching how nested C arrays are stored. `layout_left` is the order many linear-algebra libraries expect. `layout_stride` covers views that skip elements: every other row, a sub-rectangle of a larger image with a row pitch, or a transposed view. The layout changes only the arithmetic; the buffer and the logical coordinates stay the same, which is why a row-major and a column-major copy of one image both report the same value for `img[1, 2]`. ## Indexing with C++23's multidimensional subscript C++23 allows `operator[]` to take several arguments, so an mdspan is indexed as `img[r, c]`. Before C++23, `img[r, c]` meant the comma operator, `img[c]`, which C++20 deprecated inside subscripts. Other useful members: - `extent(i)` returns the size of dimension `i`; `rank()` returns the number of dimensions. - `stride(i)` returns the step between consecutive indices in dimension `i`: 3 and 1 for a row-major 2 by 3 view, 1 and 2 for column-major. - `size()` returns the product of the extents; `data_handle()` returns the underlying pointer. Indexing is unchecked: each index must be less than its extent, or the behaviour is undefined. The C++26 draft adds a checked `at()`, which libc++ implements in release 23. ## Static extents and object size Static extents move sizes into the type, as with `std::span<T, N>`. With libc++, a `std::mdspan<float, std::extents<std::size_t, 2, 3>>` is 8 bytes, only the pointer, while the dynamic 2D view is 24 bytes, a pointer plus two sizes. That size is libc++'s choice, not a requirement. The more important effect is that the compiler can fold constant strides into the index arithmetic. ## What came after C++23 The C++26 draft extends the facility. `std::submdspan` takes slices, such as one row, one column, or a tile, and returns another mdspan with an adjusted layout. `layout_left_padded` and `layout_right_padded` describe rows padded for alignment, and `aligned_accessor` promises an over-aligned pointer. libc++ 23 does not implement `submdspan` or the padded layouts yet, so code relying on them needs a reference implementation or another standard library. ## Using it in practice - Wrap the buffer once at the API boundary and pass the mdspan by value, as you would a span. - Pick the layout that matches the producer of the data, such as a decoder emitting rows or a numerical library expecting columns, rather than copying to reorder. - Remember that mdspan, like span, never owns: the vector or allocation it points into must outlive it, and reallocating that vector leaves the view dangling. ## What interviewers listen for Name mdspan as the C++23 non-owning multidimensional view, explain extents (rank, static versus dynamic) and the layout as an index-to-offset mapping with `layout_right` as the default, show `img[r, c]` from C++23, and mention `layout_stride` or C++26's `submdspan` for sub-images.
- How would you view a 64 by 64 tile inside a larger row-major image with std::mdspan in C++23?Use `std::layout_stride`: point the data handle at the tile's top-left pixel and give extents 64 by 64 with strides of the full image width for rows and 1 for columns. The view then skips the rest of each row without copying. The C++26 draft's `submdspan` would compute this from slice arguments.
- What does img[1, 2] mean on a pre-C++23 compiler?Before C++23, a comma inside brackets is the comma operator, so `img[1, 2]` evaluates `1`, discards it and indexes with `2`; C++20 deprecated that use. C++23 makes it a call to a multi-argument `operator[]`, which mdspan provides.
- Says std::mdspan owns and allocates its elements like a 2D vector
- Thinks std::layout_right means column-major order
- Believes changing the layout policy reorders the data in memory
- Assumes std::submdspan is part of C++23
- Says mdspan indexing throws on an out-of-range index
Assumes C++23, which added std::mdspan and multidimensional operator[]; submdspan, padded layouts and mdspan::at() are C++26 draft additions.