beautypg.com

The distance and advance primitives – HP Integrity NonStop H-Series User Manual

Page 217

background image

Iterator union_aux(Iterator first1, Iterator last1,
Iterator first2, Iterator last2,
Iterator Result,
random_access_iterator_tag)
{
// More efficient implementation
}

} // End of my_namespace

The iterator primitive iterator_category() returns a tag that selects and uses the best available
implementation of the algorithm. In order for iterator_category() to work, the iterator provided to
the algorithm must be either a simple pointer type, or derived from one of the basic Standard
C++ Library iterator types. When you use the iterator_category() primitive, the default
implementation of the algorithm should expect at most a forward iterator. This default version
will be used if the algorithm encounters an iterator that is not a simple pointer or derived from a
basic standard iterator. (Note that input and output iterators are less capable than forward
iterators, but that the requirements of an algorithms generally mandate read/write capabilities.)

The distance and advance Primitives

The value_type primitive lets you determine the type of value pointed to by an iterator.
Similarly, you can use the distance_type primitive to get a type that represents distances between
iterators.

In order to efficiently find the distance between two iterators, regardless of their capabilities, you
can use the distance primitive. The distance primitive uses the technique shown above to send a
calling program to one of four different implementations. This offers a considerable gain in
efficiency, since an implementation for a forward iterator must step through the range defined by
the two iterators:

Distance d = 0;
while (start++ != end)
d++;

whereas an implementation for a random access iterator can simply subtract the start iterator
from the end iterator:

Distance d = end - start;

Similar gains are available with the advance primitive, which allows you to step forward (or
backward) an arbitrary number of steps as efficiently as possible for a particular iterator.

This manual is related to the following products: