Check out the new USENIX Web site. next up previous contents
Next: Adaptors Up: Generic Programming and the Previous: Algorithms

Iterators

Iterators are implementations of structural abstractions and are data type templates exported by container classes. Iterators are generalizations of array pointers for generic containers and provide operators to traverse the range of data they point to and also operators to reference the element they point to. Typically, the pointer arithmetic operators like ++ (auto-increment), - (auto-decrement), +n (jump n positions forward), and -n (jump n positions backward), are overloaded to provide traversal implementations. They also overload the comparison operators (==, <, >, ) and the assignment operator (=) to compare iterator positions and allow iterator assignments, respectively. The C++ * operator is overloaded to reference the element at the position pointed to by the iterator. Algorithms work over iterators rather than directly over containers. Therefore the same algorithm can work for different container types as long as they export appropriate types of iterators. An additional advantage of having algorithms work on iterators instead of on containers is that algorithms can be used to work on a partial range of elements in a container.

An iterator can be of one of the following kinds - input, output, forward, bidirectional, or random-access. Input iterators are data sources (e.g. the cin standard input object in C++), and output operators are data sinks (e.g. cout in C++). Forward iterators satisfy properties of both input and output iterators. Forward iterators can be traversed one position at a time only in the forward direction, hence they support only the ++ operator. Bidirectional iterators satisfy properties of forward iterators, can be traversed in both forward and reverse directions one step at a time, and support the - operator. Random access iterators are bidirectional iterators, which can make non-unit jumps in the forward or reverse direction. They support the +n and -n operators too.

Most container classes export member functions called begin() and end() which return iterators that point to the first element and past the last element, respectively, of the container object. Starting with these functions, and using the iterator traversal operators, users can construct iterators pointing to a subrange of the elements in a container.


next up previous contents
Next: Adaptors Up: Generic Programming and the Previous: Algorithms

Sundaresan Neelakantan
Thu May 15 16:11:49 PDT 1997