通常的 STL 结构是:
A usual STL construct is:
vector<string> col;
copy(istream_iterator<string>(cin), istream_iterator<string>(),
back_inserter(col));
我们使用 istream_iterator
从 std 输入 (cin
) 复制到向量.
where we use an istream_iterator
to copy from std input (cin
) to a vector.
谁能解释一下这段代码是如何工作的?
Can anyone explain how this code works?
我的问题是我不太明白这部分:
my problem is that I don't really understand this part:
istream_iterator<string>(cin), istream_iterator<string>()
首先,请注意,在这种情况下,根本没有必要使用 std::copy
.您可以直接从迭代器初始化向量:
First, note that in this case, there's no real need to use std::copy
at all. You can just initialize the vector directly from the iterators:
vector<string> col((istream_iterator<string>(cin)),
istream_iterator<string>());
不过,这可能不会使代码更容易理解.
This probably doesn't make the code a whole lot easier to understand though.
就代码的工作方式而言,它可能比您想象的要简单一些.一个 istream_iterator 看起来像这样:
As far as how the code works, it's probably a little more straighforward than you think. An istream_iterator looks vaguely like this:
template <class T>
class istream_iterator {
std::istream *is;
T data;
public:
istream_iterator(std::istream &is) : is(&is) { ++(*this); }
istream_iterator() : is(nullptr) {}
T operator++() { (*is) >> data; return *this; }
T operator++(int) { (*is) >> data; return *this; }
T const &operator*() { return data; }
bool operator !=(istream_iterator &end) { return (*is).good(); }
bool operator ==(istream_iterator &end) { return !(*is).good(); }
};
显然我要跳过的还有更多,但这就是我们在这里关心的大部分内容.因此,当您创建迭代器时,它会从流中读取(或尝试)一个项目到我称为 data
的变量中.当您取消引用迭代器时,它会返回 data
.当您增加迭代器时,它会读取(或尝试)从文件中读取下一项.尽管编写时好像将一个迭代器与另一个迭代器进行比较,operator==
和 operator!=
实际上只是检查文件的结尾1.
Obviously there's more more I'm skipping over, but that's most of what we care about here. So, what happens is that when you create the iterator, it reads (or attempts to) an item from the stream into the variable I've called data
. When you dereference the iterator, it returns data
. When you increment the iterator, it reads (or attempts to) the next item from the file. Despite being written as if they compare one iterator to another, operator==
and operator!=
really just check for the end of the file1.
然后被 std::copy
使用,它(再次简化)看起来像这样:
That's then used by std::copy
, which (again simplified) looks vaguely like this:
template <class InIt, class OutIt>
void std::copy(InIt b, InIt e, OutIt d) {
while (b != e) {
*d = *b;
++b;
++d;
}
}
因此,这从输入迭代器中读取和项目,将该项目写入输出迭代器,并重复直到当前位置的迭代器比较等于输入末尾的迭代器(这将发生在您到达文件结尾).请注意,与其他迭代器不同,istream 迭代器允许您使用的唯一结束"位置是文件的末尾.
So, this reads and item from the input iterator, writes that item to the output iterator, and repeats until the iterator for the current position compares equal to the iterator for the end of the input (which will happen when you reach the end of the file). Note that unlike other iterators, the only "end" position you're allowed to use with an istream iterator is the end of the file.
这篇关于std::copy 如何与流迭代器一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!