Skip to content

std::flat_map (C++23) ​

In a nutshell ​

A sorted map that swaps the red-black tree for a contiguous array — faster lookups (cache-friendly), more compact memory, but O(n) insertion and erasure.

#include <flat_map>

Core API Cheat Sheet ​

OperationSignatureDescription
Access elementV& operator[](const K& key)Access by key; inserts a default value if the key is absent
Finditerator find(const K& key)Returns an iterator to the element
Insertpair<iterator, bool> insert(const value_type&)Inserts a key-value pair
Erasesize_t erase(const K& key)Removes the element with the given key
Element countsize_t size() constReturns the number of elements
Is emptybool empty() constChecks whether the container is empty
Clearvoid clear()Removes all elements
Iterationiterator begin() / end()Traverses in key order
Lower/upper bounditerator lower_bound(const K&)Finds boundaries in sorted order
Containsbool contains(const K& key) const(Available since C++23) Checks whether a key exists

Minimal Example ​

C++
// Standard: C++23
#include <flat_map>
#include <iostream>

int main() {
    std::flat_map<int, const char*> m;
    m[1] = "one";
    m[3] = "three";
    m[2] = "two";

    for (const auto& [k, v] : m) {
        std::cout << k << ": " << v << "\n";
    }
    // 1: one  2: two  3: three  (sorted by key)

    std::cout << std::boolalpha << m.contains(2) << "\n"; // true
}

Embedded Applicability: Medium ​

  • Contiguous storage is CPU-cache-friendly; lookups on small datasets far outperform std::map
  • No per-node allocator overhead and less memory fragmentation — a good fit for embedded environments with tight heap space
  • Insertion/erasure is O(n), so it is unsuitable for large datasets that change frequently
  • Compiler support is still landing (GCC 15+, Clang 20+, MSVC STL not yet); evaluate your toolchain before production use

Compiler Support ​

GCCClangMSVC
152019.51

See Also ​


Some content is referenced from cppreference.com, used under the CC-BY-SA 4.0 license

pdf-latest-4-g85128cc · 85128cc · 2026-10-05