beautypg.com

Stream iterators, Input stream iterators, Output stream iterators – HP Integrity NonStop H-Series User Manual

Page 32: Output stream, Iterators

background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

Stream Iterators

Stream iterators are used to access an existing input or output stream using iterator operations.

Input Stream Iterators

Stream Iterators

As we noted in the discussion of input iterators, the standard library provides a mechanism to
turn an input stream into an input iterator. This ability is provided by the class istream_iterator.
When declared, the two template arguments are the element type, and a type that measures the
distance between elements. Almost always the latter is the standard type ptrdiff_t. The single
argument provided to the constructor for an istream_iterator is the stream to be accessed. Each
time the ++ operator is invoked on an input stream iterator a new value from the stream is read
(using the >> operator) and stored. This value is then available through the use of the
dereference operator (operator *). The value constructed by istream_iterator when no arguments
are provided to the constructor can be used as an ending iterator value. The following, for
example, finds the first value 7 in a file of integer values.

istream_iterator intstream(cin), eof;
istream_iterator::iterator where =
find(intstream, eof, 7);

The element denoted by an iterator for an input stream is valid only until the next element in the
stream is requested. Also, since an input stream iterator is an input iterator, elements can only
be accessed, they cannot be modified by assignment. Finally, elements can be accessed only
once, and only in a forward moving direction. If you want to read the contents of a stream more
than one time, you must create a separate iterator for each pass.

Output Stream Iterators

The output stream iterator mechanism is analogous to the input stream iterator. Each time a
value is assigned to the iterator, it will be written on the associated output stream, using the >>
operator. To create an output stream iterator you must specify, as an argument with the
constructor, the associated output stream. Values written to the output stream must recognize
the stream >> operation. An optional second argument to the constructor is a string that will be
used as a separator between each pair of values. The following, for example, copies all the

This manual is related to the following products: