A class output_iterator that satisfies the requirements of an output iterator for the value type T, supports the following operations.
Algorithms on input iterators should never attempt to pass through the same iterator twice. They should be single pass algorithms.
| |
|
The following code fragment reads numbers of the type double from cin and computes their sum. The STL provides an ostream_iterator that fulfills the output iterator requirements. As the iterator is a kind of file pointer it should be clear why only single pass algorithms can be applied on this iterator.
{ ostream_iterator<double> it(cout); for(int r = 0; r < 10; r++){ *it = 3.1415 * r * r; ++it; } }
The above code fragment is equivalent to:
{ for(int r = 0; r < 10; r++){ cout << 3.1415 * r * r; } }
The use of output iterators is better illustrated with a function that can write into arbitrary containers:
template < class OutputIterator > void generator(OutputIterator it) { for(int r = 0; r < 10; r++){ *it = 3.1415 * r * r; ++it; } }
and here comes its usage.
{ ostream_iterator<double> it(cout); generator(it); double R[10]; generator(R); }
Note that the memory where the function generator writes to must be allocated. If you want to insert the generated doubles at the end of a list you have to use a back_insert_iterator. To explain this is out of the scope of this introduction to the STL. Please refer to the STL reference manuals.