[英]Writing a C++20 range to standard output
I can take several int
s from a vector
putting them to standard output with an iterator:我可以从一个
vector
中取出几个int
,将它们放入带有迭代器的标准 output :
std::vector<int> v{0,1,2,3,4,5};
std::copy_n(v.begin(),
3,
std::ostream_iterator<int>(std::cout, ":"));
I can use the new C++20 ranges to take several int
s from a vector
putting them to standard output with |
我可以使用新的 C++20 范围从
vector
中获取几个int
,并将它们放入标准 output 和|
operator in a for
loop, one value at a time using <<
. for
循环中的运算符,一次使用一个值<<
。
for(int n : std::views::all(v)
| std::views::take(3))
{
std::cout << n << '/';
}
How can I put the results of std::views::all(v) | std::views::take(3)
我怎样才能把
std::views::all(v) | std::views::take(3)
std::views::all(v) | std::views::take(3)
to standard output w/o explicitly looping through values? std::views::all(v) | std::views::take(3)
到标准 output 没有显式循环值?
Something like:就像是:
std::views::all(v)
| std::views::take(4)
| std::ostream_iterator<int>(std::cout, " ");
or或者
std::cout << (std::views::all(v)
| std::views::take(4));
The specific thing you're looking for is using the new ranges algorithms:您正在寻找的具体内容是使用新的范围算法:
std::ranges::copy(v | std::views::take(4),
std::ostream_iterator<int>(std::cout, " "));
You don't need to use views::all
directly, the above is sufficient.不需要直接使用
views::all
,以上就足够了。
You can also use fmtlib, either directly:您也可以直接使用 fmtlib:
// with <fmt/ranges.h>
// this prints {0, 1, 2, 3}
fmt::print("{}\n", v | std::views::take(4));
or using fmt::join
to get more control (this lets you apply a format string to each element in addition to specifying the delimiter):或使用
fmt::join
获得更多控制权(除了指定分隔符外,这还允许您将格式字符串应用于每个元素):
// this prints [00:01:02:03]
fmt::print("[{:02x}]\n", fmt::join(v | std::views::take(4), ":"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.