Search code examples
c++fmt

Print vector with {fmt} using different styles for different elements


Can I print the elements of a vector with fmt using different styles for different elements? Something like:

#include <vector>
#include <string>

// fmt library
#define FMT_HEADER_ONLY
#include <fmt/core.h>
#include <fmt/ranges.h>
#include <fmt/color.h>

int main() {

    std::vector<std::string> V;
    int i = 0;
    V.push_back(fmt::format(fg(fmt::color::red), "{}", i++));
    V.push_back(fmt::format(fg(fmt::color::green), "{}", i));
    fmt::print("{}\n", V);
}

I know it could be achieved by manually iterating over V and printing each element with a styled fmt::print, but is there a way to do it more "elegantly" by somehow reusing the standard vector formatter?


Solution

  • Formatting elements individually is probably the easiest but you could also use fmt::styled in combination with ranges. For example (godbolt):

    #include <vector>
    #include <string>
    #include <ranges>
    
    #include <fmt/ranges.h>
    #include <fmt/color.h>
    
    int main() {
      std::vector<std::string> v = {"red", "green"};
      fmt::print(
        "{}\n",
        v | std::views::transform([](const std::string& s) {
          return fmt::styled(s, fg(s == "red" ? fmt::color::red : fmt::color::green));
        }));
    }
    

    This produces the following output:

    output