C++ Iterators

Iterators are used to access members of the container classes, and can be used in a similar manner to pointers. For example, one might use an iterator to step through the elements of a vector. There are several different types of iterators:

IteratorDescription
input_iteratorRead values with forward movement. These can be incremented, compared, and dereferenced.
output_iteratorWrite values with forward movement. These can be incremented and dereferenced.
forward_iteratorRead or write values with forward movement. These combine the functionality of input and output iterators with the ability to store the iterators value.
bidirectional_iteratorRead and write values with forward and backward movement. These are like the forward iterators, but you can increment and decrement them.
random_iteratorRead and write values with random access. These are the most powerful iterators, combining the functionality of bidirectional iterators with the ability to do pointer arithmetic and pointer comparisons.
reverse_iteratorEither a random iterator or a bidirectional iterator that moves in reverse direction.

Each of the container classes is associated with a type of iterator, and each of the STL algorithms uses a certain type of iterator.

For example, vectors are associated with random-access iterators, which means that they can use algorithms that require random access. Since random-access iterators encompass all of the characteristics of the other iterators, vectors can use algorithms designed for other iterators as well.

The following code creates and uses an iterator with a vector:

    vector<int> the_vector;
    vector<int>::iterator the_iterator;
 
    for( int i=0; i < 10; i++ ) the_vector.push_back(i);
    int total = 0;
    the_iterator = the_vector.begin();
    while( the_iterator != the_vector.end() ) {
      total += *the_iterator;
      ++the_iterator;
    }
 
    cout << "Total=" << total << endl;

Notice that you can access the elements of the container by dereferencing the iterator.

Related topics: http://www.oreillynet.com/pub/a/network/2005/10/18/what-is-iterator-in-c-plus-plus.html