Skip to main content

8.1) Using Iterators to Access Containers


Consider the typical pattern for manipulating all elements of a vector:

vector<double> v;
...
for (int i = 0; i < v.size(); ++i) {
  // Do something with v[i]
}

This is a perfectly reasonable approach to follow if you only ever use vectors, but it assumes the use of indexing by position and therefore cannot be used with containers that don't support this notion - i.e., lists, sets, maps.

A more general approach that works with all kinds of containers is needed, and this is provided by iterators.