C++ Notes: STL Iterators - Introduction

An iterator is used to move thru the elements an STL container (vector, list, set, map, ...).

Each type of container has an underlying implementation (eg, vector or linked list) for which there is a "natural" way to get to the next element (incrementing a pointer for vectors, following the next or prev pointer for lists, ...). Iterators are defined within each of the container classes to work specifically with that type of container. An iterator may be as simple as a pointer, or may be defined as a class. Regardless of the implementation, the same operators are defined.

Why iterators are so useful

Kinds of iterators

There are several types of iterators, but most often you will use either bidirectional (list) or random iterators (vector, deque, array), which have all the operations of bidirectional iterators and more. Because so many algorithms only require bidirectional access, they can be applied to all containers.

Some of the other types are as follows. Forward iterators move only forward over the elements of a container. Input iterators that move only in a forward direction, at most one time, and can only access values. Output iterators that move only in a forward direction, at most one time, and can only write values.

Constant iterators

To preserve constantness there are both non-constant and constant versions of iterators