beautypg.com

Forward iterators, Bidirectional iterators – HP Integrity NonStop H-Series User Manual

Page 29

background image

As we noted earlier, ordinary pointers, as well as all the iterators constructed by containers in the
standard library, can be used as examples of output iterators. (Ordinary pointers are random access
iterators, which are a superset of output iterators.) So, for example, the following code fragment
copies elements from an ordinary C-style array into a standard library vector:

int data[100];
vector newdata(100);
...
copy (data, data+100, newdata.begin());

Just as the istream_iterator provided a way to operate on an input stream using the input iterator
mechanism, the standard library provides a data type, ostream_iterator, that permits values to be
written to an output stream in an iterator-like fashion. These will be described in

Output Stream

Iterators

.

Yet another form of output iterator is an insert iterator. An insert iterator changes the output iterator
operations of dereferencing/assignment and increment into insertions into a container. This permits
operations such as copy() to be used with variable length containers, such as lists and sets. Insert
iterators will be described in more detail in

Insert Iterators

.

Forward Iterators

A forward iterator combines the features of an input iterator and an output iterator. It permits values
to both be accessed and modified. One function that uses forward iterators is the replace() generic
algorithm, which replaces occurrences of specific values with other values. This algorithm is written
as follows:

template
void
replace (ForwardIterator first, ForwardIterator last,
const T& old_value, const T& new_value)
{
while (first != last)
{
if (*first == old_value)
*first = new_value;
++first;
}
}

Ordinary pointers, as well as any of the iterators produced by containers in the standard library, can
be used as forward iterators. The following, for example, replaces instances of the value 7 with the
value 11 in a vector of integers.

replace (aVec.begin(), aVec.end(), 7, 11);

Bidirectional Iterators

A bidirectional iterator is similar to a forward iterator, except that bidirectional iterators support the
decrement operator (operator --), permitting movement in either a forward or a backward direction

This manual is related to the following products: