我不明白为什么我需要将另一个迭代器作为调用 std::copy()
以读取文件的第二个参数。迭代器如何结束文件?
vector<Point> v;
istream_iterator<Point> is(file), end;
copy(is, end, back_inserter(v));
最佳答案
How is iterator 'end' ending of a file?
按照惯例和/或标准库中的设计决定。迭代器 end
是默认构造的,在 cppreference 上,我们了解默认的 std:istream_iterator
构造函数:
constexpr istream_iterator();
Constructs the end-of-stream iterator, value-initializes the stored value [...]
更深层的原因是标准算法是围绕半开范围的概念构建的,通常表示为[first, last)
。 is
迭代器必须与某种结束标记 last
区分开来 - 否则,std::copy
无法知道何时从输入中读取不再有意义(即,当它到达文件末尾时)。在您的例子中,这是 end
。
关于c++ - 为什么我需要另一个迭代器作为 std::copy() 中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57866465/