ranges/tosorted.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 <set>
#include <ranges>
#include <cctype>

int main()
{
  std::vector<std::string> coll{"Rome", "Berlin", "Kiev", "LA", "Tokyo", "Cairo"};
  std::println("coll: {}", coll);

  auto gt2 = [] (auto s) { return s.size() > 2; };
  auto tolower = [] (std::string s) {
                   s[0] = static_cast<char>(std::tolower(s[0]));
                   return s;
                 };
  auto v = coll
            | std::views::filter(gt2)               // significant size
            | std::ranges::to<std::multiset>()      // sorted
            | std::views::transform(tolower)        // with lowered first character
            ;  

  std::println("v:    {}", v);
}