Learning Hub Search Ctrl K

Modern C++ › C++23

mdspan and flat_map

Multidimensional views and contiguous associative containers.

Since C++23 advanced #mdspan#flat_map#flat_set#multidimensional#subscript-operator#containers#cache

Explanation

std::mdspan (<mdspan>) is a non-owning, multidimensional view over a contiguous block of memory: std::span generalized to N dimensions. It never allocates; it only maps indices to offsets.

std::mdspan m(data, rows, cols);     // view data as rows x cols
m[i, j] = 1.0;                        // C++23 multidimensional subscript operator

Template parameters: mdspan<Element, Extents, LayoutPolicy, AccessorPolicy>.

  • Extents (std::extents<size_t, 3, 4> fully static, std::dextents<size_t, 2> dynamic): each dimension may be known at compile time or run time.
  • Layout controls the index-to-memory mapping: layout_right (row-major, the C++ default), layout_left (column-major, Fortran/BLAS), layout_stride (arbitrary strides, slicing).
  • Use m.extent(0), m.rank() and m.data_handle(). Slicing with submdspan arrives in C++26.

std::flat_map / std::flat_set (<flat_map>, <flat_set>) are associative containers stored in sorted contiguous arrays (one for keys, one for values) instead of a node-based tree. Lookups use binary search. Compared to std::map:

map (red-black tree) flat_map (sorted vectors)
Lookup O(log n), cache-unfriendly O(log n), cache-friendly, usually faster
Iteration pointer chasing linear scan, very fast
Insert / erase O(log n), stable iterators O(n) shifting, iterators invalidated
Memory one node allocation per element compact

Choose flat_map for read-mostly data built once (configuration, lookup tables).

Example

#include <iostream>
#include <mdspan>
#include <vector>

int main() {
    // --- mdspan: a 3x4 matrix over a flat vector (row-major)
    std::vector<int> storage(12);
    std::mdspan grid(storage.data(), 3, 4);              // CTAD: dynamic extents 3 x 4

    for (std::size_t i = 0; i < grid.extent(0); ++i)
        for (std::size_t j = 0; j < grid.extent(1); ++j)
            grid[i, j] = static_cast<int>(i * 10 + j);   // multi-index subscript

    std::cout << grid[2, 3] << " " << storage[2 * 4 + 3] << " " << grid.rank() << "\n";   // 23 23 2

    // column-major view over the same type of storage
    std::mdspan<int, std::dextents<std::size_t, 2>, std::layout_left> colMajor(storage.data(), 3, 4);
    colMajor[1, 2] = 7;
    std::cout << storage[1 + 2 * 3] << "\n";             // 7: element (1,2) is at offset row + col*rows

    // fixed-size 2x2 with compile-time extents
    int small[4] = {1, 2, 3, 4};
    std::mdspan<int, std::extents<std::size_t, 2, 2>> m2(small);
    std::cout << m2[1, 0] << "\n";                       // 3
    return 0;
}

flat_map has the same interface as std::map. This program needs a standard library that ships <flat_map> (GCC 15, libc++ 20; it is not in the MSVC toolset 14.44 I tested), so it is not runnable on every setup:

#include <flat_map>
#include <iostream>
#include <string>

int main() {
    std::flat_map<std::string, int> stock{{"pear", 2}, {"apple", 5}};
    stock["cherry"] = 9;
    stock.insert_or_assign("apple", 6);
    for (const auto& [name, qty] : stock)                // iterates in sorted order
        std::cout << name << "=" << qty << " ";          // apple=6 cherry=9 pear=2
    std::cout << "\n" << stock.contains("pear") << stock.size() << "\n";   // 13
}

Common pitfalls

  • mdspan doesn’t own memory: the storage must outlive it, and its size must be at least the product of the extents.
  • Row-major vs column-major confusion causes silent wrong results when exchanging data with BLAS/Fortran. State the layout explicitly.
  • grid[i, j] needs a C++23 compiler; before that use grid(i, j) in earlier implementations (Kokkos reference) or data[i * cols + j].
  • Inserting into a flat_map shifts elements: O(n) per insert, so build from a pre-sorted range or insert in bulk (insert(std::sorted_unique, ...)).
  • flat_map invalidates iterators, pointers and references on every insert/erase (unlike map).
  • Support differs by feature. mdspan compiled here on MSVC 14.44 (VS 2022 17.14), and GCC 14 and libc++ 17 also have it. flat_map was missing from MSVC 14.44; GCC 15 and libc++ 20 ship it. Check your library before relying on either.

Legacy vs modern

// C++98: hand-rolled indexing, or vector<vector<int>> (scattered rows, slower)
std::vector<int> m(rows * cols);
int at(int i, int j) { return m[i * cols + j]; }
std::vector<std::vector<int> > m2(rows, std::vector<int>(cols));
// C++23
std::mdspan m(data, rows, cols);  m[i, j]

Sorted-vector-as-a-map was a well-known manual trick (and boost::container::flat_map); std::flat_map standardizes it. Compare with Associative Containers and std::span.

Exercises

1. A mdspan<int, dextents<size_t,2>> of 4x5: at what offset is element (2, 3) in row-major order?

2 * 5 + 3 = 13.