gpt4 book ai didi

c++ - 为什么从分配给变量的 istream_iterator 读取不起作用?

转载 作者:行者123 更新时间:2023-12-03 06:51:46 24 4
gpt4 key购买 nike

我编写了以下程序,从 std::cin 读取 3 个数字,并将它们输出到 std::cout , 并执行两次:

#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
std::copy_n(std::istream_iterator<int>(std::cin),
3,
std::ostream_iterator<int>(std::cout, " "));

std::copy_n(std::istream_iterator<int>(std::cin),
3,
std::ostream_iterator<int>(std::cout, " "));
}
对于 1 2 3 4 5 6 的输入,程序 prints预期 1 2 3 4 5 6 .

由于我发现代码有点冗长,我尝试将迭代器存储在变量中:
#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
auto ins = std::istream_iterator<int>(std::cin);
auto outs = std::ostream_iterator<int>(std::cout, " ");

std::copy_n(ins, 3, outs);
std::copy_n(ins, 3, outs);
}
但现在输入 1 2 3 4 5 6 ,程序 prints 1 2 3 1 4 5 .
我不明白输出。这里发生了什么,我做错了什么?
另外,请注意,只有在我使用 ins 时才重要。 .我是否使用 outs不影响输出。

最佳答案

this reference :

std::istream_iterator is a single-pass input iterator that reads successive objects of type T from the std::basic_istream object for which it was constructed, by calling the appropriate operator>>. The actual read operation is performed when the iterator is incremented, not when it is dereferenced. The first object is read when the iterator is constructed. Dereferencing only returns a copy of the most recently read object.


因此,当您第一次创建 ins 时变量,它显示为 1来自 cin立即并缓存它。
如果你看 copy_n() 的声明,输入迭代器按值传递,这意味着它被复制。
template< class InputIt, class Size, class OutputIt >
OutputIt copy_n( InputIt first, Size count, OutputIt result );
为了论证,我们假设以下 copy_n() 的实现正在使用(检查您的编译器以了解实际实现):
template< class InputIt, class Size, class OutputIt>
OutputIt copy_n(InputIt first, Size count, OutputIt result)
{
if (count > 0) {
*result++ = *first;
for (Size i = 1; i < count; ++i) {
*result++ = *++first;
}
}
return result;
}
当您通过 inscopy_n() , 缓存 1被复制到 first范围。当 copy_n()取消引用 first ,它接收缓存的 1并输出到 result .然后 copy_n()增量 first上面写着 2来自 cin并缓存它,然后取消引用 first接收 2并输出它,然后递增 first内容为 3来自 cin并缓存它,然后取消引用 first接收 3并输出,然后退出。
当您通过 inscopy_n()再次,原始缓存 1还在 ins并复制到 first范围。当 copy_n()取消引用 first ,它接收缓存的 1并输出到 result .然后 copy_n()增量 first上面写着 4来自 cin并缓存它,然后取消引用 first接收 4并输出它,然后递增 first内容为 5来自 cin并缓存它,然后取消引用 first接收 5并输出,然后退出。

关于c++ - 为什么从分配给变量的 istream_iterator 读取不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64475418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com