使用FMT的格式范围而无需封闭[]括号

发布于 2025-01-21 06:31:22 字数 674 浏览 1 评论 0原文

我想用 saparator打印一系列值,但没有[]使用FMT库。

如果我尝试打印出这样的范围,那么

std::vector v {8,4,7,2};
std::cout  << fmt::format("{}",v) <<"\n";

输出为

[8、4、7、2]

但是我实际上希望输出为

8、4、7、2

我该怎么做?


我发现的一种方法是执行以下操作

std::cout  << fmt::format("{}",fmt::join(v,", ")) <<"\n";  

。但是,它是冗长的,它给FMT打了2个电话, 我想避免。这可能吗?

demo

另外,由于性能和可读性原因,我对删除[] 来自FMT产生的字符串。

I want to print a range of values with , separator but without [] using fmt library.

If I try to print out some range like this

std::vector v {8,4,7,2};
std::cout  << fmt::format("{}",v) <<"\n";

the output is

[8, 4, 7, 2]

But I actually want the output to be

8, 4, 7, 2

How can I do this?


One approach I've found is to do the following

std::cout  << fmt::format("{}",fmt::join(v,", ")) <<"\n";  

which does work. However, it's verbose, and it makes 2 calls to fmt,
which I would like to avoid. Is this possible?

demo

Also, due to performance and readability reasons I am not interested in removing [] from the string produced by fmt.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神也荒唐 2025-01-28 06:31:22

较短的代码是使用fmt直接执行打印,而不是仅将其用于格式化,然后将结果传递到常规cout iostream方法:

fmt::print("{}\n", fmt::join(v, ", ")); // Optionally, I believe you can use the literals to make the format string compile-type checked, "{}\n"_format

格式字符串也包含了新线,print同时进行格式和打印,因此比以下格式更短/不复杂。

std::cout << fmt::format("{}", fmt::join(v, ", ")) << "\n";  

The shorter code is to use fmt to do the printing directly, rather than just using it to format, then passing the result to normal cout the iostream way:

fmt::print("{}\n", fmt::join(v, ", ")); // Optionally, I believe you can use the literals to make the format string compile-type checked, "{}\n"_format

The format string incorporates the newline as well, and print does both the formatting and printing, so it's markedly shorter/less complex than:

std::cout << fmt::format("{}", fmt::join(v, ", ")) << "\n";  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文