< Previous | Contents | Next >
After I declare a vector for the hero’s inventory and add the same three string
objects from the previous incarnations of the program, I declare an iterator.
vector<string>::iterator myIterator;
The preceding line declares an iterator named myIterator for a vector that contains string objects. To declare an iterator of you own, follow the same pattern. Write the container type, followed by the type of objects the container will hold (surrounded by the < and > symbols), followed by the scope resolution operator (the :: symbol), followed by iterator, followed by a name for your new iterator.
So what are iterators? Iterators are values that identify a particular element in a container. Given an iterator, you can access the value of the element. Given the right kind of iterator, you can change the value. Iterators can also move among elements via familiar arithmetic operators.
A way to think about iterators is to imagine them as Post-it notes that you can stick on a specific element in a container. An iterator is not one of the elements, but a way to refer to one. Specifically, I can use myIterator to refer to a particular element of the vector inventory. That is, I can stick the myIterator
126 Chapter 4 n The Standard Template Library: Hangman
Post-it note on a specific element in inventory. Once I’ve done that, I can access the element or even change it through the iterator.
Next, I declare another iterator.
vector<string>::const_iterator iter;
The preceding line of code creates a constant iterator named iter for a vector that contains string objects. A constant iterator is just like a regular iterator except that you can’t use it to change the element to which it refers; the element must remain constant. You can think of a constant iterator as providing read- only access. However, the iterator itself can change. This means you can move iter all around the vector inventory as you see fit. You can’t, however, change the value of any of the elements through iter. With a constant iterator the Post- it can change, but the thing it’s stuck to can’t.
Why would you want to use a constant iterator if it’s a limited version of a regular iterator? First, it makes your intentions clearer. When you use a constant iterator, it’s clear that you won’t be changing any element to which it refers. Second, it’s safer. You can use a constant iterator to avoid accidentally changing a container element. (If you attempt to change an element through a constant iterator, you’ll generate a compile error.)
Tra p
Using push_back() might invalidate all iterators referencing the vector.
Is all of this iterator talk a little too abstract for you? Are you tired of analogies about Post-it notes? Fear not—next, I put an actual iterator to work.