flat/flatsetinit.cpp

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. Creative Commons License

// raw code

#include <print>
#include <string>
#include <vector>
#include <ranges>
#include <flat_set>

int main()
{
  // init from an initializer list:
  std::flat_set<std::string> fs1{"Kiev", "Tokyo", "Berlin", "Rio"};
  std::println("fs1:   {}\n", fs1);

  // init from a range/view:
  std::vector<std::string> names{"tic", "tac", "toe"};
  std::println("names: {}", names);
  std::flat_set fs2{std::from_range, names};
  std::println("fs2:   {}\n", fs2);

  // init with a sorting criterion for ascending:
  std::flat_set<std::string, std::greater<>>
         fs3{std::from_range, names | std::views::stride(2)};
  std::println("fs3:   {}\n", fs3);
}