We use iterators with sequences (also called ranges). These sequences can be in containers, or they can be input sequences or output sequences. The program of Fig. 15.4 demonstrates input from the standard input (a sequence of data for input into a program), using an istream_iterator, and output to the standard output (a sequence of data for output from a program), using an ostream_iterator. The program inputs two integers from the user at the keyboard and displays the sum of the integers. As you’ll see later in this chapter, istream_iterator
s and ostream_iterator
s can be used with the Standard Library algorithms to create powerful statements. For example, you can use an ostream_iterator
with the copy
algorithm to copy a container’s entire contents to the standard output stream with a single statement.
1 // Fig. 15.4: fig15_04.cpp
2 // Demonstrating input and output with iterators.
3 #include <iostream>
4 #include <iterator> // ostream_iterator and istream_iterator
5 using namespace std;
6
7 int main()
8 {
9 cout << "Enter two integers: ";
10
11 // create istream_iterator for reading int values from cin
12 istream_iterator< int > inputInt( cin );
13
14 int number1 = *inputInt; // read int from standard input
15 ++inputInt; // move iterator to next input value
16 int number2 = *inputInt; // read int from standard input
17
18 // create ostream_iterator for writing int values to cout
19 ostream_iterator< int > outputInt( cout );
20
21 cout << "The sum is: ";
22 *outputInt = number1 + number2; // output result to cout
23 cout << endl;
24 } // end main
Enter two integers: 12 25
The sum is: 37