Navigation: Up, Table of Contents, Bibliography, Index, Title Page

Output Iterator (iterator)

Definition

A class 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.

Creation

iterator it;
iterator it ( iterator it1);

Operations

iterator& it = iterator it1 Assignment.
bool it == iterator it1 Test for equality: Two iterators are equal if they refer to the same item.
bool it != iterator it1 Test for inequality. The result is the same as !(it == it1).
T& * it Returns a reference to the value of the iterator. This operator can only be used in order to assign a value to this reference.
iterator& ++ it Prefix increment operation.
Precondition: it is dereferenceable.
void it ++ Postfix increment operation. The result is the same as that of iterator tmp = it; ++it; return tmp;.
Precondition: it is dereferenceable.

Example

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.


Return to chapter: Iterators
Navigation: Up, Table of Contents, Bibliography, Index, Title Page
The CGAL Project. Mon, June 30, 1997.