C++ Reference ยท Containers
C++23 std::mdspan
Reference for C++23 std::mdspan: a non-owning multidimensional view over contiguous data, extents, layouts, the multidimensional operator[] and why this site's runner lacks it.
std::mdspan (C++23, header <mdspan>) is the multidimensional sibling of std::span. It does not own memory. It maps a tuple of indices such as (row, column) onto a flat contiguous buffer, so one std::vector<double> can be viewed as a matrix, a 3D volume or an image without copying and without nested vectors.
The view is described by three parts: the element type, the extents (the size of each dimension, each either fixed at compile time or dynamic), and a layout policy that says how indices become offsets. The default layout is row-major (std::layout_right, like C arrays); std::layout_left is column-major (like Fortran), and std::layout_stride lets you describe arbitrary strides, which is how sub-views and transposes are made.
The <mdspan> header is not available on this site's runner (GCC 15.2). The code on this page is read-only and shows the C++23 API; it needs a standard library that ships <mdspan> (for example a newer GCC, a recent Clang with libc++, or MSVC). The runnable examples below show the same indexing logic written by hand.
#include <mdspan> #include <vector> std::vector<int> data(6); std::mdspan m(data.data(), 2, 3); // 2 rows, 3 columns, dynamic extents m[1, 2] = 7; // C++23 multidimensional operator[]
Try it
The first example is the hand-written equivalent, which does run: a small class that views a flat vector as a matrix, which is exactly what mdspan automates.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
The same program with the real C++23 mdspan (read-only here, because the runner has no <mdspan>):
#include <iostream> #include <mdspan> #include <vector> int main() { std::vector<int> flat(2 * 3); std::mdspan m(flat.data(), 2, 3); // extents deduced: dynamic, dynamic for (std::size_t r = 0; r < m.extent(0); ++r) { for (std::size_t c = 0; c < m.extent(1); ++c) { m[r, c] = static_cast<int>(10 * r + c); // multidimensional subscript } } // Expected output of the loop above, flat storage: 0 1 2 10 11 12 // Column-major view of the same kind of buffer std::mdspan<int, std::dextents<std::size_t, 2>, std::layout_left> colMajor(flat.data(), 2, 3); // Static extents: sizes are part of the type std::mdspan<int, std::extents<std::size_t, 2, 3>> fixed(flat.data()); }
Syntax
template <class T, class Extents, class LayoutPolicy = std::layout_right, class AccessorPolicy = std::default_accessor<T>> class mdspan; std::extents<std::size_t, 2, 3> // both known at compile time std::dextents<std::size_t, 2> // two dynamic extents std::extents<std::size_t, std::dynamic_extent, 3> // mixed constexpr reference operator[](Indices... idx) const; // C++23: m[i, j, k] constexpr size_type extent(rank_type r) const; // size of dimension r static constexpr rank_type rank() noexcept; constexpr size_type size() const noexcept; // product of extents constexpr T* data_handle(); // the underlying pointer
| Name | Description |
|---|---|
T |
Element type. |
Extents |
Sizes of the dimensions, static or dynamic. |
LayoutPolicy |
layout_right (row-major, default), layout_left (column-major), layout_stride, and since C++26 layout_left_padded and layout_right_padded. |
AccessorPolicy |
How an offset becomes a reference; customize it for atomics, aligned access or proxies. |
Returns: operator[] returns a reference to the element; size() the total element count; extent(r) the length of dimension r.
Errors / undefined behavior: indices outside the extents are undefined (precondition). The buffer must hold at least size() elements and outlive the view. Dereferencing an empty mdspan is undefined.
Usage notes
- C++23 multi-index subscript:
m[i, j]is only possible because C++23 allowsoperator[]to take several arguments (see operator overloading). In C++20 code you would writem(i, j). - Non-owning, like
span: it never allocates and never frees. Keep the buffer alive. - Layouts decide performance. Iterate so the last index in a
layout_rightview changes fastest to keep memory access sequential. - Static extents let the compiler unroll loops and drop bounds data from the object; mix them (
extents<size_t, dynamic_extent, 3>) for "any number of rows, three columns". - Sub-views come from
std::submdspan(C++26), which is separate from C++23mdspan. - Availability: the header is missing on this site's runner (GCC 15.2 in
-std=c++23mode), so themdspanexamples are read-only. Check your own toolchain's standard library before relying on it. - Alternatives: nested
std::vector<std::vector<T>>is easy but fragments memory; a flat vector with manual index math is the usual fallback.
Related
- std::span, std::array, std::vector
- Lessons: Multidimensional arrays, std::span