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 <vector>
#include <ranges>
#include <flat_map>
int main()
{
// init from an initializer list:
std::flat_map<std::string, double> fm1{{"Kiev", 3.0}, {"Tokyo", 36.9},
{"Berlin", 3.9}, {"Rio", 6.8}};
std::println("fm1: {}\n", fm1);
// init from a range/view:
std::vector<std::string> names{"tic", "tac", "toe"};
std::println("names: {}", names);
std::flat_map<int, std::string> fm2{std::from_range,
names | std::views::enumerate};
std::println("fm2: {}\n", fm2);
// init with two containers (one for the keys, one for the values):
std::vector vals{1.1, 2.2, 3.3};
std::println("vals: {}", vals);
std::flat_map fm3{names, vals}; // OK: same size
std::println("fm3: {}\n", fm3);
// init with a sorting criterion for ascending:
std::flat_map<int, std::string, std::greater<>>
fm4{std::from_range, names | std::views::enumerate};
std::println("fm4: {}\n", fm4);
// init with a range that is already sorted:
std::ranges::sort(names);
std::flat_map fm5{std::sorted_unique, names, vals}; // OK: sorted
std::println("fm5: {}", fm5);
}