The following code example is taken from the book
C++23 - The Complete Guide
by Nicolai M. Josuttis,
Leanpub, 2026
The code is licensed under a
Creative Commons Attribution 4.0 International License.
// raw code
#include <print>
#include <string>
#include <memory>
#include <flat_map>
void printCapaAndAddrOf(const auto& fm, const std::string& key)
{
std::print("{}\n", fm);
std::print(" size: {}, capa: {}\n", fm.size(), fm.keys().capacity());
auto&& posBeg = fm.begin(); // print address of first element (if any)
if (posBeg != fm.end()) {
std::print(" begin: {:15}", *posBeg);
const void* addr = &(posBeg->first);
std::print("at: {}\n", addr);
}
auto&& posFirst = fm.find(key); // print element address of passed key (if any)
if (posFirst != fm.end()) {
std::print(" {:5}: {:15}", key, *posFirst);
const void* addr = &(posFirst->first);
std::print("at: {}\n", addr);
}
std::print("\n");
}
int main()
{
std::flat_map<std::string, double> fm;
auto beg0 = fm.begin();
printCapaAndAddrOf(fm, "");
const std::string firstKey = "elem0"; // insert an element we later search
fm.emplace(firstKey, 1);
auto beg1 = fm.begin();
printCapaAndAddrOf(fm, firstKey);
fm.emplace("zzlast", 2); // insert a new last element
auto beg2 = fm.begin();
printCapaAndAddrOf(fm, firstKey);
fm.emplace("aafirst", 3); // insert a new first element
auto beg3 = fm.begin();
printCapaAndAddrOf(fm, firstKey);
fm.emplace("ccsecond", 4); // insert a new second element
auto beg4 = fm.begin();
printCapaAndAddrOf(fm, firstKey);
std::println("beg0 == beg1: {}", beg0 == beg1);
std::println("beg1 == beg2: {}", beg1 == beg2);
std::println("beg2 == beg3: {}", beg2 == beg3);
std::println("beg3 == beg4: {}", beg3 == beg4);
}