MORE ON ITERATORS

The iterator header defines several templates for iterators that transfer data from a source to a destination. Stream iterators act as pointers to a stream for input or output, and they enable you to transfer data between a stream and any source or destination that works with iterators, such as an algorithm. Inserter interators can transfer data into a basic sequence container. The iterator header defines two stream iterator templates, istream_iterator<T> for input streams and ostream_iterator<T> for output streams, where T is the type of object to be extracted from, or written to, the stream. The header also defines three inserter templates, inserter<T>, back_inserter<T>, and front_inserter<T>, where T is the type of sequence container in which data is to be inserted.

Let’s explore some of these iterators in a little more depth.

Using Input Stream Iterators

Here’s an example of how you create an input stream iterator:

istream_iterator<int> numbersInput(cin);

This creates the iterator numbersInput of type istream_iterator<int> that can point to objects of type int in a stream. The argument to the constructor specifies the stream to which the iterator relates, so this is an iterator that can read integers from cin, the standard input stream.

The default istream_iterator<T> constructor creates an end-of-stream iterator, which will be equivalent to the end iterator for a container that you have been obtaining by calling the end() function. Here’s how you could create ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.