format/formatelems.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 <list>
#include <chrono>
using namespace std::literals;

int main()
{
  // print floating point elements:
  std::vector<double> coll{0, 8.8, 15, 47.11, -1, 42};
  std::println("coll:   {}", coll);                     // default
  std::println("  .2:   {::.2f}\n", coll);              // 2 digits after dot

  // print nested collections without and with hexadecimal values:
  std::vector<std::list<int>> coll2d{{1, 1, 1}, {47, 11}, {0, 8, 15}};
  std::println("coll2d: {}", coll2d);
  std::println("   hex: {:::02X}\n", coll2d);

  // print collection with timepoints:
  auto now = std::chrono::system_clock::now();
  std::vector dates{now, now + 8h};
  std::println("dates:  {::%F %X}", dates);
  std::println("times:  {::%R}", dates);
}