iterator adaptors - stream iterators

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值