Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Formatting ranges and tuples

Use case

Print containers directly with std::print/std::format.

Explanation

std::print and std::format now support ranges and tuples. Format specs like :#x apply to elements.

Code

// Formatting ranges is not fully implemented everywhere yet.
// https://en.cppreference.com/w/cpp/compiler_support/23.html
#if defined(__APPLE__)
#include <map>
#include <print>
#include <tuple>
#include <vector>

int main() {
  std::vector<int> addrs = {0x1000, 0x1100, 0x1200};
  std::map<std::string, int> symbols = {{"_main", 0x1000}, {"_helper", 0x1100}};

  std::println("Addresses: {::#x}", addrs);
  std::println("Symbols: {}", symbols);

  return 0;
}
#else
int main() { return 0; }
#endif

View on GitHub.

Output

$ ./src/c++23/build/formatting-ranges-and-tuples
Addresses: [0x1000, 0x1100, 0x1200]
Symbols: {"_helper": 4352, "_main": 4096}