format/printranges.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 <list>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <ranges>

int main()
{
  // sequential containers:
  std::println("vector:        {}", std::vector{"tic", "tac", "toe"});
  std::println("list:          {}", std::list{"tic", "tac", "toe"});
  std::string arr[] = {"tic", "tac", "toe"};
  std::println("raw array:     {}", arr);
  std::println("string:        {}\n", std::string{"abc"});

  // associative containers:
  std::set<std::string> set{"tic", "tac", "toe"};
  std::println("set:           {}", set);
  std::println("unordered set: {}\n", std::unordered_set{"tic", "tac", "toe"});

  // key/value containers:
  std::map<int,char> map{{1, 'a'}, {2, 'b'}, {3, 'c'}};
  std::unordered_map<int,char> umap{{1, 'a'}, {2, 'b'}, {3, 'c'}};
  std::println("map:           {}", map);
  std::println("unordered map: {}\n", umap);

  // views switch to layout of vectors (of pairs):
  std::println("view on set:   {}", set | std::views::all);
  std::println("view on map:   {}", map | std::views::all);
}