Start Stl invalidating iterators

Stl invalidating iterators

They're also quite flexible -- if you change the underlying container, it's easy to change the associated iterator so long as you only use features associated with the iterator supported by both classes.

First, iterators are distinguished by whether you can use them for reading or writing data in the container.

Some types of iterators allow for both reading and writing behavior, though not necessarily at the same time.

This can be a problem if you happen to exceed the bounds of your iterator by stepping forward (or backward) by too many elements.

The following code demonstrates both the use of random access iterators and exceeding the bounds of the array (don't run it!

For instance, if you want to access the elements of an STL vector, it's best to use an iterator instead of the traditional C-style code.

The strategy is fairly straightforward: call the container's begin function to get an iterator, use to step through the objects in the container, access each object with the * operator ("*iterator") similar to the way you would access an object by dereferencing a pointer, and stop iterating when the iterator equals the container's end iterator. = to check for inequality, == to check for equality.

For instance, to erase an entire vector: Note that various container class support different types of iterators -- the vector class, which has served as our model for iterators, supports a random access iterator, the most general kind.