43.2 Differences between Stream Iterators and Container Iterators

In contrast to regular container iterators, stream iterators can provide only non-modifiable read-only access or write-only access to their elements. The istream_iterator template is an InputIterator that can access but not modify elements. The ostream_iterator tempate, on the other hand, is an OutputIterator that provides write-only access to streams.

Each time the istream_iterator object invokes operator++(), a new value from the stream is read and stored in value of type T, where T is the type of the element being written. The cached value, which by definition cannot be overwritten by assignment, is then available through the use of the dereferencing operator*(). This behavior of storing elements in the iterator is unique to istream_iterators.

Also unlike container iterators, stream iterators can access elements only once, and only in the forward-moving direction, so that they can work only with one-pass algorithms. If the contents of the stream are to be read more than once, separate iterators must be created for each pass. Due to this unique nature of InputIterators it is inadvisable to use more than one istream_iterator with the same stream object at the same time.

The istream_iterator has a template parameter named Distance, with the default value of std::ptrdiff_t (which is defined in <cstddef>), although the Distance parameter is not used in the implementation. There is no distance type template argument for ostream_iterator, since pure OutputIterators do not have the notion of distance!