ranges/views1.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 <iostream>
#include <string>
#include <map>
#include <ranges>

int main()
{
  // map of composers (mapping their name to their year of birth):
  std::map<std::string, int> composers{
    {"Bach", 1685},
    {"Beethoven", 1770},
    {"Chopin", 1810},
    {"Mozart", 1756},
    {"Tchaikovsky", 1840},
    {"Vivaldi ", 1678},
  };

  // iterate over the names of the first three composers born since 1700:
  for (const auto& elem : composers
                           | std::views::filter([](const auto& y) {
                                                  return y.second >= 1700;
                                                })           // born since 1700
                           | std::views::take(3)             // first three
                           | std::views::keys                // keys/names only
                           ) {
    std::cout << "- " << elem << '\n';
  }
}