In this example, we use istream_iterator and copy () to convert CIN to a vector. We only need a line of program, and the vector passes through sort (). Then we use ostream_iterator to convert the vector to cout, you only need one line of program.
1 /*
(2) oomusou 2006
Http://oomusou.cnblogs.com
3
4 filename: streamiteratorcincout. cpp
5 Compiler: Visual C ++ 8.0/iso c ++
6 Description: Demo how to use istream_iterator From CIN to Vector
7 and ostream_iterator from vector to cout
8 release: 12/07/2006
9 */
10
11 # include <iostream>
12 # include <vector>
13 # include <algorithm>
14 # include <string>
15 # include <iterator>
16
17 using namespace STD;
18
19int main (){
20 vector <string> SVEC;
21
22 // copy CIN to Vector
23 copy (istream_iterator <string> (CIN), istream_iterator <string> (), back_inserter (SVEC ));
24
25 // sort Vector
26 sort (SVEC. Begin (), SVEC. End ());
27
28 // copy vector to cout
29 copy (SVEC. Begin (), SVEC. End (), ostream_iterator <string> (cout, "\ n "));
30}
Istream_iterator <string> (CIN) on the 23th line, which means converting CIN into stream_iterator <string> This template class, and the bone is string. Istream_iterator <string> () calls its default constructor to automatically generate an EOF.
The 23-line copy () operation also uses back_inserter. Because the premise of generic algorithm is that the container size cannot be changed, the member function of the container cannot be called, however, the insert action is bound to change the size of the container and the member function of the container is required. Therefore, we have to use back_inserter to call the member function of the container.
The 29-row ostream_iterator <string> (cout, "\ n") converts ostream_iterator into a cout and uses "\ n" for line feed. Why not use STD: Endl? Because the signature of ostream_iterator requires the use of const char *, the string cannot be entered.