c++ - Control {fmt} formatting of nested containersranges - Stack Overflow

If I have a range I can print it with the fmt library, in this way: 8.1.0api.html#ranges-api#include

If I have a range I can print it with the fmt library, in this way: /8.1.0/api.html#ranges-api

#include <fmt/ranges.h>

std::vector<int> t = {1, 2, 3};
// Prints "[1, 2, 3]"
fmt::print("{}", t);

And if I want to control the separator:

// Prints "1| 2| 3"
fmt::print("{}", fmt::join(t, "| "));

What happens if I have a nested containers, for example std::vector<std::vector<int>>, how can I control the nested separator?

std::vector<std::vector<int>> v = ...
fmt::print("{}", fmt::join(t, "| "));

this will print [1, 2, 3]| [4, 5, 6]| [7, 8, 9].

Note that I can only control the top level format.


For context, I am trying to control formatting of multidimensional arrays:

If I have a range I can print it with the fmt library, in this way: https://fmt.dev/8.1.0/api.html#ranges-api

#include <fmt/ranges.h>

std::vector<int> t = {1, 2, 3};
// Prints "[1, 2, 3]"
fmt::print("{}", t);

And if I want to control the separator:

// Prints "1| 2| 3"
fmt::print("{}", fmt::join(t, "| "));

What happens if I have a nested containers, for example std::vector<std::vector<int>>, how can I control the nested separator?

std::vector<std::vector<int>> v = ...
fmt::print("{}", fmt::join(t, "| "));

this will print [1, 2, 3]| [4, 5, 6]| [7, 8, 9].

Note that I can only control the top level format.


For context, I am trying to control formatting of multidimensional arrays: https://godbolt./z/M9cTEox7c

Share Improve this question asked Nov 15, 2024 at 20:54 alfCalfC 16.4k4 gold badges79 silver badges154 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You can use ranges for that:

#include <fmt/ranges.h>

#include <ranges>
#include <vector>

int main() {
    std::vector<std::vector<int>> v = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    constexpr auto joinIntVec = [](auto& ve) { return fmt::join(ve, "~"); };

    fmt::print("{}", fmt::join(std::views::transform(v, joinIntVec), "| "));
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745671974a4639458.html

相关推荐

  • c++ - Control {fmt} formatting of nested containersranges - Stack Overflow

    If I have a range I can print it with the fmt library, in this way: 8.1.0api.html#ranges-api#include

    6小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信