ranges/tosortedcity.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 <algorithm>

class City
{
private:
  std::string _name;
public:
  City(const std::string& s = {}) : _name{s} {}
  City(const char* s) : _name{s} {}

  bool operator< (const City& p) const {
    std::println("- compare {} with {}", _name, p._name);
    return _name < p._name;
  }

  auto name() const { return _name;}
  auto size() const { return _name.size();}
};

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

  auto sizeGt2 = [] (const auto& s) { return s.size() > 2; };
  auto toLower = [] (const City& c) {
                   std::string s = c.name();
                   std::println("- transform {}", s);
                   s[0] = static_cast<char>(std::tolower(s[0]));
                   return s;
                 };

  std::println("*** init view (without applying it):");
  auto sizeGt2Sorted = std::views::filter(sizeGt2)          // significant size
                        | std::ranges::to<std::multiset>()  // sorted
                        | std::views::transform(toLower)    // name with lowered first char
                        ;

  std::println("\n*** apply view:");
  auto v = coll | sizeGt2Sorted;     // expensive: sorts all elements

  std::println("\n*** print view:");
  std::println("cities: {}", v);     // applies transform(toLower)
}