Input iterator reads forward and is provided by istream

You're viewing an older version of this page (#4211). View the current version.

View versions (1)

Description

Input iterator moves only forward and may retrieve but not store values, provided by istream.

Input iterators can read elements only once. To progress to the next value or end of sequence, you increment it (post or pre-increment).

Two input iterators are equal if they occupy the same position. But this does NOT mean that they return the same value on element access!

Operations

ExpressionDescription
*iProvides read access to the actual element
i->mProvides read access to a member of the actual element
++iSteps forward and returns new position (when not null)
i++Steps forward and returns old position (when not null)
i1==i2Returns if i1 is equal to i2
i1!=2Returns if i1 is not equal to i2
TYPE(i)Copies iterator (copy constructor)

References

Example 1
Problem

This program illustrates the use of the istream_iterator and ostream_iterator in conjunction with the copy algorithm to provide vector I/O.

Workings
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
  int a[] = {1, 2, 3, 4, 5};
  vector<int> v(a, a+5);
  cout <<"\nInitial contents of v, displayed using the copy "
         "algorithm to copy values from\nv to the standard output "
         "with the help of an ostream_iterator:\n";
  copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));

  cout <<"\nNow we copy some values from standard input into a vector "
         "\nusing the copy algorithm and an istream_iterator.\nEnter five "
         "integer values, followed by your end-of-file character:\n";

  copy(istream_iterator<int>(cin), istream_iterator<int>(), v.begin());

  cin.ignore(80, '\n');
  cin.clear();

  cout << "\nFinal contents of v: ";
  copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));

  return 0;
}
Solution

Output:

Initial contents of v, displayed using the copy algorithm to copy values from
v to the standard output with the help of an ostream_iterator:
1 2 3 4 5

Now we copy some values from standard input into a vector
using the copy algorithm and an istream_iterator.
Enter five integer values, followed by your end-of-file character:
2 4 6 8 10
^Z

Final contents of v: 2 4 6 8 10

See Also