beautypg.com

Input iterators – HP Integrity NonStop H-Series User Manual

Page 27

background image

random access iterator ordinary pointers

vector
deque

In the following sections we will describe the capabilities and construction of each form of iterator.

Input Iterators

Input iterators are the simplest form of iterator. To understand their capabilities, consider an example
program. The find() generic algorithm (to be described in more detail in

Chapter 13:

Find an Element

Satisfying a Condition

), performs a simple linear search, looking for a specific value being held within a

container. The contents of the container are described using two iterators, here called first and last.
While first is not equal to last the element denoted by first is compared to the test value. If equal, the
iterator, which now denotes the located element, is returned. If not equal, the first iterator is
incremented, and the loop cycles once more. If the entire region of memory is examined without
finding the desired value, then the algorithm returns the end-of-range iterator.

template
InputIterator
find (InputIterator first, InputIterator last, const T& value)
{
while (first != last && *first != value)
++first;
return first;
}

This algorithm illustrates three requirements for an input iterator:

An iterator can be compared for equality to another iterator. They are equal when they point to
the same position, and are otherwise not equal.

An iterator can be dereferenced using the * operator, to obtain the value being denoted by the
iterator.

An iterator can be incremented, so that it refers to the next element in sequence, using the
operator ++.

Notice that these characteristics can all be provided with new meanings in a C++ program, since the
behavior of the given functions can all be modified by overloading the appropriate operators. Because
of this overloading, iterators are possible. There are three main varieties of input iterators:

Ordinary pointers. Ordinary pointers can be used as input iterators. In fact, since we can subscript
and add to ordinary pointers, they are random access values, and thus can be used either as input or
output iterators. The end-of-range pointer describes the end of a contiguous region of memory, and
the deference and increment operators have their conventional meanings. For example, the following
searches for the value 7 in an array of integers:

Ordinary Pointers as Iterators

int data[100];
...

This manual is related to the following products: