Iterators

What are iterators?

Iterators are objects that allow access to the data structure with which they are associated, in a standard way. Typically, that access is sequential, although RandomAccessIterator also is available.

Here is a video discussing the general idea of iterators... the code is in Java, but it is a good explanation of what iterators are for, whatever language we are using them in:

The iterator design pattern

Ranged for loops with iterators

In our course, we will first use iterators to allow the implementation of ranged-for loops for collections. For this, our iterator class should implement 3 methods: an equality operator, a dereference operator, and an increment operator. The iterator should also store a way to access the current value in the collection, and have a constructor.

begin and end

The collection that utilizes the iterator should have 2 other methods: begin() and end(). begin() should return an iterator that, when de-referenced, yields the first element of the collection, and end() should return an iterator that signals that the end of the collection has been reached. begin() and end() define a half-open range which is inclusive on the side of begin() and exclusive on end(). Once you reach the end(), you know that you are out of bounds and should stop iterating.

Declaring STL iterators

Many of the Standard Template Library algorithms take iterators as arguments to indicate where an algorithm should begin and end its work. For instance, find will look for an item within the range given by the begin and end arguments. This means one can search the entire collection for the value sought, or any contiguous subset of the collection. If you import an STL container you can specify its iterator by writing "::iterator" after the STL class name. For example, to specify the iterator for a vector of characters, you would write: "vector<char>::iterator" .

If you want to treat the item an iterator returns when de-referenced as constant, you can instead use: "::const_iterator"

External Links