format/printranges1.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>

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

int main()
{
  // ranges of values:
  std::println("vector<string>:");
  printValueRange(std::vector<std::string>{"tic", "tac", "toe"});
  std::println("\nset<string>:");
  printValueRange(std::set<std::string>{"tic", "tac", "toe"});
  std::println("\nRaw array of strings:");
  std::string arr[] = {"tic", "tac", "toe"};
  printValueRange(arr);
  std::println("\nView on set<string>:");
  printValueRange(std::set{"tic", "tac", "toe"} | std::views::all);

  // ranges of chars:
  std::println("\nvector<char>:");
  std::println(" default:   {}", std::vector<char>{'a', '\t', 'b'});
  std::println(" {{::?}} :    {::?}", std::vector<char>{'a', '\t', 'b'});
  std::println(" {{::}} :     {::}", std::vector<char>{'a', '\t', 'b'});
  std::println(" {{:s}} :     {:s}", std::vector<char>{'a', '\t', 'b'});
}