flat/flatset1.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 <flat_set>

int main()
{
  std::flat_set coll{3, 5, 8, 9, 11, 13, 17};    // initialize flat set without duplicates
  std::println("coll: {}", coll);

  coll.insert(15);                               // insert one element (if not in yet)
  coll.insert(99);                               // insert one element (if not in yet)
  coll.insert(99);                               // no effect unless a flat multiset is used
  std::println("coll: {}", coll);

  coll.insert({0, 8, 23});                       // inserts multiple elements (not in yet)
  std::println("coll: {}", coll);

  auto pos5 = coll.find(5);                      // fast
  auto pos23 = coll.find(23);                    // fast
  for (auto pos = pos5; pos != pos23; ++pos) {   // elements from 5 to before 23
    std::print("{} ", *pos);
  }
  std::println("");

  coll.erase(8);                                 // remove element with value 8
  coll.erase(13);                                // remove element with value 13
  std::println("coll: {}", coll);
}