A stream iterator is an iterator adapter that allows you to use a stream as a source or destination of algorithms. In particular, an istream iterator
can be used to read elements from an input stream, and an ostream iterator can be used to write values to an output stream. stream buffer iterator is a special one, which can be used to read from or write to a stream buffer directly.
Four kinds of stream iterators:
1) ostream_iterator: The implementation of an ostream iterator uses the same concept as the implementation of insert iterators. The only difference is that they transform the assignment of a new value
into an output operation by using operator <<.
Operations:

Examples:
ostream_iterator<int> intWriter(cout,"\n");
// write elements with the usual iterator interface
*intWriter = 42; // call cout.operat << () internally
*intWriter = 77;
...
vector<int> coll = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
copy (coll.cbegin(), coll.cend(), ostream_iterator<int>(cout," < "));
2) istream_iterator: reading failure (due to end-of-file or an error) cause the istream iterator becomes end-of-stream iterator.
Operations

Examples:
istream_iterator<int> intReader(cin);
// create end-of-stream iterator
istream_iterator<int> intReaderEOF;
while (intReader != intReaderEOF) {
cout << "once: " << *intReader << endl;
cout << "once again: " << *intReader << endl;
++intReader; // call cin.operator >>() internally
}
input:
1 2 3 f 4
// 'f' ends the program due to the format error, the stream is no longer in a good state.
//Therefore, the iterator becomes the end-of-stream iterator.
// stream buffer iterators provide iterators that conform to input iterator or output iterator requirements
// and read or write individual characters from stream buffers.
// The class templates istreambuf_iterator<> and ostreambuf_iterator<> are used to read
// or to write individual characters from or to objects of type basic_streambuf<>, respectively
3) ostreambuf_iterator
Operations:

Examples:
std::ostreambuf_iterator<char> bufWriter(std::cout);
std::string hello("hello, world\n");
std::copy(hello.begin(), hello.end(), // source: string
bufWriter); // destination: output buffer of cout
4) istreambuf_iterator
Operations:

Examples:
istreambuf_iterator<char> inpos(cin);
istreambuf_iterator<char> endpos;
ostreambuf_iterator<char> outpos(cout);
while (inpos != endpos) {
*outpos = *inpos; // assign its value to the output iterator
++inpos;
++outpos;
}
本文介绍了四种类型的流迭代器:ostream_iterator、istream_iterator、ostreambuf_iterator 和 istreambuf_iterator。详细解释了它们的操作原理及应用场景,并提供了丰富的代码示例。
481

被折叠的 条评论
为什么被折叠?



