For the iterator, there is another way to use streams and standard functions. The main point of understanding is to treat the input/output stream as a container. Therefore, any algorithm that accepts the iterator parameters can work with the stream.
Listing 4. outstrm. cpp
# Include <iostream. h>
# Include <stdlib. h> // need random (), srandom ()
# Include <time. h> // need time ()
# Include <algorithm> // need sort (), copy ()
# Include <vector> // need vector
Using namespace STD;
Void display (vector <int> & V, const char * s );
int main()
{
// Seed the random number generator
srandom( time(NULL) );
// Construct vector and fill with random integer values
vector<int> collection(10);
for (int i = 0; i < 10; i++)
collection[i] = random() % 10000;;
// Display, sort, and redisplay
Display(collection, "Before sorting");
sort(collection.begin(), collection.end());
Display(collection, "After sorting");
return 0;
}
// Display label s and contents of integer vector v
void Display(vector<int>& v, const char* s)
{
cout << endl << s << endl;
copy(v.begin(), v.end(),
ostream_iterator<int>(cout, "/t"));
cout << endl;
}
The display () function shows how to use an output stream iterator. The following statement transfers the values in the container to the cout output stream object:
copy(v.begin(), v.end(),
ostream_iterator<int>(cout, "/t"));
The third parameter instantiates the ostream_iterator <int> type and uses it as the output target iterator object of the copy () function. The "/t" string is used as a separator. Running result:
$ g++ outstrm.cpp
$ ./a.out
Before sorting
677 722 686 238 964 397 251 118 11 312
After sorting
11 118 238 251 312 397 677 686 722 964
This is the magic of STL 』. To define the output stream iterator, STL provides a template class. Ostream_iterator. The constructor of this class has two parameters: An ostream object and a string value. Therefore, you can create an iterator object as follows:
ostream_iterator<int>(cout, "/n")
This iteration can be used with any function that accepts an output iterator. Fromhttp: // blog.csdn.net/zdl1016/archive/2007/03/01/1517798.aspx