Using IteratorsTopIterators in C++

Iterators in C++

The STL provides 5 different kinds of iterators: input, output, forward, bidirectional, and random access. The key to understanding iterators is to think of them as pointers with special operations.

All iterators support "==", "!=", and "*", where "*" is used to get the next value from the iterators. Thus it1 == it2 implies *it1 == *it2.

Input Iterators

Input iterators are used for reading values from a container, but need not allow changing the container in any way. (Those that do not are labelled as const iterators.) Also support ++it and it++ to allow forward movements through the structure.

Example of an iterator that prints out all of the values in a vector:

    vector<int> v;
     ... stuff to add data ...
     for(vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
        cout << *it << endl;
     }

Notice that the type is associated with the container class. Virtually all container classes support iterators begin() and end() that are iterators that initially refer to the first element of the collection and "one past" the last element of the collection. Thus, when an iterator == v.end() then it has finished processing the last element of the list.

Notice that there is no such type as "input iterator". It is a concept, but the algorithms of the STL are written in terms of those concepts. For example the built in find function requires an input iterator, which means that it needs to support "++" (in both forms) as well as the standard iterator operations. It's implementation looks like:

  template <class InputIterator, class T>
  InputIterator find(InputIterator first, InputIterator last, const T& value) {
      while (first != last && *first != value) {
         ++first;
      }
      return first;
  }

(Note that class and typename can be used interchangeably with templates.)

Output iterators

Output iterators are like input iterators, but the dereferencing operator (*) is used to set values rather than read them.

Forward Iterators

Forward iterators are input and output, but also guarantee that each time through they will return elements in the same order (input and output make no such guarantees).

Bidirectional iterators

Bidirectional iterators are like forward iterators, but also support "-" to go backwards.

Random-access Iterators

Supports it+n or n+it. Also, it += n moves the iterator along n places (efficiency depends on the implementation). For example,

    template<class RandomAccessIterator>
    void sort(RandomAccessIterator first, RandomAccessIterator last)

indicates that will jump around in collection to sort.

const_iterators

Most iterators come in two flavors. E.g.,

    iterator begin();
    const_iterator begin() const;
    iterator end();
    const_iterator end() const;

Because const is part of signature, have different signatures and automatically chooses the correct one.


Using IteratorsTopIterators in C++