< Previous | Contents | Next >

Declaring Iterators

After I declare a vector for the heros 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 Ive 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 cant 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 cant, however, change the value of any of the elements through iter. With a constant iterator the Post- it can change, but the thing its stuck to cant.

Why would you want to use a constant iterator if its a limited version of a regular iterator? First, it makes your intentions clearer. When you use a constant iterator, its clear that you wont be changing any element to which it refers. Second, its 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, youll generate a compile error.)


Tra p

image

Using push_back() might invalidate all iterators referencing the vector.

image


Is all of this iterator talk a little too abstract for you? Are you tired of analogies about Post-it notes? Fear notnext, I put an actual iterator to work.