Writing Iterators

Iterators

Often times, we need to loop over all elements in the "container".

Code to "run through all elements" can look very different for different containers.

C++ iterators unify these different code segments.


There are many different iterators with different types provided for the container classes in STL.

Defining Custom Iterators

If we make our own container class from scratch to represent, say, a deck of cards, it would be nice to have an iterator for the deck.


We define an entirely new class to represent an iterator.


Suppose we want to output the elements in MyContainerType c, we use the iterator in this way:

for (MyContainerType::iterator it = c.begin(), c != c.end(); ++it) {
	//*it can now be used to refer to each successive element
	std::cout << *it < " ";
}

Therefore we need to overload the

A real world iterator might also overload:

In addition to overload these operators, the enclosing (containing) class (MyContainerType) should also define methods named begin and end, which return iterators to the first item in the collection, and the just-past-last element in the collection, respectively.