Format Ranges in C++23

Format Ranges in C++23

Displaying collections of data in a readable way is a frequent need in modern applications. Ranges such as vectors, arrays, and maps often require formatted output for logging, debugging, or reporting purposes. Traditionally, printing these containers typically involved writing loops or using helper functions, which could be verbose and error-prone.

Since C++23, the std::format provides direct support for ranges. This means that containers like std::vector, std::map, and other can be inserted into formatted strings directly, producing clear and uniform output without manual iteration or conversion.

The following example shows how to format a vector and a map for console output:

#include <iostream>
#include <format>
#include <vector>
#include <map>

int main() {
    std::vector v = {1, 2, 3};
    std::map<int, int> m = {{1, 10}, {2, 20}};
    std::string str = std::format("{} {}", v, m);

    std::cout << str << std::endl; // [1, 2, 3] {1: 10, 2: 20}

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.