[   ^ to index...   |   <-- previous   |   next -->   ]

Iterators

From what we have seen so far, we don't gain anything in container flexibility or interchangeability by using this vector over any other vector. The key to making containers interchangeable (as much as possible) is the addition of iterators:

template <class T> vector { public: // ... everything on the previous page, plus: typedef /* ... */ iterator; typedef /* ... */ const_iterator; iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const; reverse_iterator rbegin(); const_reverse_iterator rbegin() const; // etc. for the reverse iterators };

What is the point of these methods? Well, think of an iterator as a "cursor" that can point to various elements in a collection. Iterators come in several varieties, but all iterators provide three essential operations (besides the obvious one of element access):

We covered these concepts when we discussed collection classes. However, STL iterators are designed to look like pointers. Therefore, element access and update/advance are implemented as overloaded operators. The following iterates over the items in a vector:

vector<int> v; for (vector<int>::iterator i = v.begin(); i != v.end(); i++) cout << *i << endl;

The analogy is with an array, for which the equivalent would be:

int a[LENGTH]; for (int* i = &a[0]; i != &a[LENGTH]; i++) cout << *i << endl;

Last modified: Wed Aug 16 18:35:42 PDT 2000