CS 70

Iterator Rules

As we've previously mentioned, iterators either refer to actual values stored in our data structure, or refer to a special non-existent just-past-the-end location.

The following rules apply to all iterators in C++:

  • You must not use * on a just-past-the-end iterator—we're past the end, so there is no item to access!
  • You must not use ++ on a just-past-the-end iterator—we're already past the end, so you can't move “beyond past-the-end”.
  • You must not compare iterators that have different origins (e.g., if you have two lists, you aren't allowed to compare iterators between those lists, only iterators within the same list).

You are required to obey these rules. C++ doesn't say what will happen if you break the rules (i.e., our old friend undefined behavior). Your program could crash; your code could appear to work (but maybe just this time, or maybe with subtle errors); or something else entirely might happen.

Here's some code that might misuse iterators:

std::list<std::string> myList;                          //  1

std::list<std::string>::iterator = myList.begin();      //  2
while (iter != myList.end()) {                          //  3
    cout << *iter << ", ";                              //  4
    ++iter;                                             //  5
}                                                       //  6

++iter;                                                 //  7

What's wrong with this code?

(When logged in, completion status appears here.)