# C++: STL: Iterators for vector

An iterator is used to move thru the elements an STL container (vector, list, set, map, ...) in a similar way to array indexes or pointers. The * operator dereferences an iterator (ie, is used to access the element an iterator points to) , and ++ (and -- for most iterators) increments to the next element.

## Iterating over a vector with subscripts

Passing over all the elements of a vector is simple, and is usually done using subscripts instead of an iterator. The main advantage of an iterator is that it can be used by many of the functions in <algorithms>. Subscripts provide an easy, familiar way to access vector elements in much the way that array elements would be accessed.

    //--- Iterating over vector with subscript.
    vector<int> v;
    . . .
    for (int i=0; i<v.size(); i++) {
        cout << v[i] << endl;
    }

## Iterators are similar to pointers

In fact, vectors iterators are usually implemented as pointers. If you feel comfortable using pointers to iterate over an array, you will feel comfortable using an iterator. For review, here is an example of one way to use a pointer to iterate over an array. Note that `&a[n]` is the address of the element after the last value currently in the array.

    //--- Iterating over array with pointer.
    int a[100];
    int n = ...;   // current number of elements

We could loop over this array like this.

    for (int* p = &a[0]; p != &a[n]; p++) {
        cout << *p << endl;
    }

or

    for (int* p = a; p != a+n; p++) {
        cout << *p << endl;
    }

## Iterating over a vector with an iterator

    //--- Iterating over vector with iterator.
    vector<int> v;
    . . .
    for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
        cout << *it << endl;
    }

## Why use iterators when subscripts work so well

There are several reasons to use iterators.

- Not always possible. Subscripts can not be used on most of the containers (eg, `list` and `map`), so you must use iterators in many cases.
- Flexible. It is easily to change underlying container types. For example, you might decide later that the number of insertions and deletions is so high that a `list` would be more efficient than a `vector`.
- Member functiuons. Many of the member functions for `vector` use iterators, for example, `assign`, `insert`, or `erase`.
- Algorithms. The `<algorithm>` functions use iterators.

## Random Access

Vector iterators are random-access.