std::views::istream with std::views::take

huangapple go评论51阅读模式
英文:

std::views::istream with std::views::take

问题

以下是您要翻译的内容:

我使用 g++ 12.2.1 编译了以下代码:

#include <iostream>
#include <ranges>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
    std::vector<int> vi;
    std::ranges::copy(std::views::istream<int>(std::cin) | std::views::take(3), std::back_inserter(vi));
    for (auto i : vi)
        std::cout << i << ' ';
}
Input:
1 2 3
4
Output: `1 2 3`

为什么我需要输入 4 个数字而不是 3 个,然后舍弃最后一个?如何解决?
英文:

I compiled the following code with g++ 12.2.1:

#include &lt;iostream&gt;
#include &lt;ranges&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;
#include &lt;iterator&gt;
int main()
{
    std::vector&lt;int&gt; vi;
    std::ranges::copy(std::views::istream&lt;int&gt;(std::cin) | std::views::take(3), std::back_inserter(vi));
    for (auto i : vi)
        std::cout &lt;&lt; i &lt;&lt; &#39; &#39;;
}

Input:

1 2 3
4

Output: 1 2 3

Why do I have to enter 4 numbers instead of 3 and discard the last one? How to solve?

答案1

得分: 6

当您输入完 1 2 3 后,views::istream&lt;int&gt;(std::cin) | views::take(3) 没有到达末尾,因为它的迭代器只指向最后一个元素,并且没有越过末尾

您可以使用 <kbd>CTRL</kbd>+<kbd>D</kbd>(在Linux中)或 <kbd>CTRL</kbd>+<kbd>Z</kbd>(在Windows中)来终止输入,就像这样:

1 2 3
Ctrl + D
英文:

When you finish typing 1 2 3, views::istream&lt;int&gt;(std::cin) | views::take(3) did not reach the end, because its iterator just points to the last element and doesn't pass the end.

You can use <kbd>CTRL</kbd>+<kbd>D</kbd> (for linux) or <kbd>CTRL</kbd>+<kbd>Z</kbd> (for Windows) to terminate the input like

1 2 3
Ctrl + D

huangapple
  • 本文由 发表于 2023年2月19日 12:53:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定