Preview: C++23 mdspan
C++23 introduces mdspan, a
multidimensional view into a contiguous memory space. It also allows
us to use the ,
operator in subscripts. This allows us to more
easily create a multidimensional array. Here’s an example:
#include <iostream>
#include <vector>
#include <mdspan>
int main() {
// create a vector with 12 elements
std::vector<double> _v(12, 0.0);
// create a 2-d view (4 rows x 3 columns) into it
auto M = std::mdspan(_v.data(), 4, 3);
// loop over rows and columns and fill the matrix
for (std::size_t i = 0; i < M.extent(0); ++i) {
for (std::size_t j = 0; j < M.extent(1); ++j) {
M[i, j] = static_cast<double>(100*i + j);
}
}
// output
for (std::size_t i = 0; i < M.extent(0); ++i) {
for (std::size_t j = 0; j < M.extent(1); ++j) {
std::cout << M[i, j] << " ";
}
std::cout << std::endl;
}
}
Note
You need a very recent compiler for this to work. I am using LLVM/clang++ 17 and build as:
clang++ -std=c++23 -stdlib=libc++ -o mdspan mdspan.cpp
On my machine (Fedora 39), I needed to install the libcxx
and
libcxx-devel
packages to get everything I need.
Tip
You can see the status of C++23 support here: compiler / library support for C++23