std::flat_map — sorted map backed by vector. std::map — tree-based map.
1#include <flat_map>2#include <map>34// std::flat_map5std::flat_map<std::string, int> fm;6fm["Alice"] = 95;7fm["Bob"] = 87;89// std::map10std::map<std::string, int> m;11m["Alice"] = 95;12m["Bob"] = 87;1314// Insertion: flat_map O(n), map O(log n)15fm.insert({"Charlie", 90}); // May shift elements16m.insert({"Charlie", 90}); // Tree rebalance1718// Search: both O(log n)19if (fm.contains("Alice")) { /* ... */ }20if (m.contains("Alice")) { /* ... */ }2122// Iteration: flat_map faster (cache-friendly)23for (const auto& [k, v] : fm) {24 // Contiguous memory25}2627// Memory: flat_map smaller (no tree nodes)28std::cout << sizeof(fm); // ~vector size29std::cout << sizeof(m); // ~3 pointers per element3031// Capacity32fm.reserve(100); // Pre-allocate33fm.shrink_to_fit(); // Release excess
When to use flat_map: