Skip to content

std::flat_map (C++23)

In a nutshell

An ordered associative container that uses a contiguous array instead of a red-black tree—faster lookups (cache-friendly) and more compact memory, but with O(n) insertion/deletion.

#include <flat_map>

Core API Cheat Sheet

OperationSignatureDescription
Access ElementV& operator[](const K& key)Access by key; inserts default value if not found
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 an element by key
Element Countsize_t size() constReturns the number of elements
Is Emptybool empty() constChecks if the container is empty
Clearvoid clear()Removes all elements
Iterateiterator begin() / end()Traverse in key order
Lower/Upper Bounditerator lower_bound(const K&)Ordered search for boundaries
Containsbool contains(const K& key) const(Since C++20) Checks if a key exists

Minimal Example

cpp
// 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  (按键序排列)

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

Embedded Applicability: Medium

  • Contiguous storage is CPU cache-friendly; lookup performance on small datasets is far superior to std::map
  • No node allocator overhead and less memory fragmentation, suitable for embedded environments with limited heap space
  • Insertion/deletion is O(n), making it unsuitable for large, frequently modified datasets
  • Compiler support is still evolving (GCC 15+, Clang 20+, MSVC 19.51+); evaluate toolchains for production use

Compiler Support

GCCClangMSVC
152019.51

See Also


Part of the content referenced from cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05