format/printranges2.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 <vector>
#include <map>
#include <utility>   // for std::pair
#include <ranges>

void printPairRange(auto&& rg)
{
  std::println(" default:   {}", rg);
  std::println(" {{:m}} :     {:m}", rg);
  std::println(" {{::m}} :    {::m}", rg);
  std::println(" {{::n}} :    {::n}", rg);
  std::println(" {{:n}} :     {:n}", rg);
  std::println(" {{:n:m}} :   {:n:m}", rg);
  std::println(" {{:n:n}} :   {:n:n}", rg);
}

int main()
{
  // ranges of pairs:
  std::println("map<int, char>:");
  std::map<int, char> map{{1, 'a'}, {2, 'b'}, {3, 'c'}};
  printPairRange(map);
  std::println("\nView on map:<int, char>");
  printPairRange(map | std::views::all);
  std::println("\nvector<pair<int, char>>:");
  std::vector<std::pair<int, char>> vecp{{1, 'a'}, {2, 'b'}, {3, 'c'}};
  printPairRange(vecp);
}