Skip to content

std::flat_map (C++23)

In a Nutshell

An ordered map backed by a contiguous array instead of a red-black tree -- faster lookups (cache-friendly), more compact memory, but O(n) insertion and deletion.

#include <flat_map>

Core API Quick Reference

OperationSignatureDescription
Access elementV& operator[](const K& key)Access by key; inserts a default value if not present
Finditerator find(const K& key)Returns an iterator to the element
Insertpair <iterator, bool> insert(const value_type&)Insert a key-value pair
Erasesize_t erase(const K& key)Remove element by key
Element countsize_t size() constReturns the number of elements
Check emptybool empty() constChecks whether the container is empty
Clearvoid clear()Removes all elements
Iterateiterator begin() / end()Traverse in key order
Lower/upper bounditerator lower_bound(const K&)Ordered boundary lookup
Containsbool contains(const K& key) const(Since C++20) Check whether 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  (sorted by key)

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

Embedded Applicability: Medium

  • Contiguous storage is CPU cache-friendly; lookup performance for small datasets far exceeds std::map
  • No per-node allocator overhead, less memory fragmentation -- suitable for embedded environments with limited heap space
  • Insertion/deletion is O(n); not suitable for large datasets with frequent modifications
  • Compiler support is still evolving (GCC 15+, Clang 20+, MSVC 19.51+); evaluate your toolchain before production use

Compiler Support

GCCClangMSVC
152019.51

See Also


Some content adapted from cppreference.com under CC-BY-SA 4.0 license

Built with VitePress