When formatting range types (like std::vector, std::array, etc.), you can use a specific syntax to control how the container and its elements are displayed.
Syntax:
[n][range_type][: range_underlying_spec]
n option: Formats the range without the opening and closing brackets (e.g., h, e, l, l, o instead of [h, e, l, l, o]).range_type: Determines the presentation style:none (default): Standard bracketed format.'s': String format. The range is formatted as a single string. Requires the range elements to be character types.'?s': Debug format. The range is formatted as an escaped string. Requires the range elements to be character types.
range_underlying_spec: A specification applied to each individual element within the range. This is parsed based on the formatter of the element's type.
Constraints:
- The
'n' option and range_underlying_spec are mutually exclusive with 's' and '?s'. - By default, ranges of characters or strings are printed escaped and quoted. However, if any
range_underlying_spec is provided (even an empty one), the elements are printed according to that specification instead.
fmt::print("{}", std::vector{10, 20, 30});
// Output: [10, 20, 30]
fmt::print("{::#x}", std::vector{10, 20, 30});
// Output: [0xa, 0x14, 0x1e]
fmt::print("{:n}", std::vector{'h', 'e', 'l', 'l', 'o'});
// Output: 'h', 'e', 'l', 'l', 'o'
fmt::print("{:s}", std::vector{'h', 'e', 'l', 'l', 'o'});
// Output: "hello"
fmt::print("{:?s}", std::vector{'h', 'e', 'l', 'l', 'o', '\n'});
// Output: "hello\n"
fmt::print("{:n:f}", std::array{std::numbers::pi, std::numbers::e});
// Output: 3.141593, 2.718282