Iterating containers

The idea of a container that is not iterable is like a car that cannot be driven. After all, a container is a collection of items. One of the common ways to iterate over container elements is to use the plain old for loop:

std::vector<int> vec{1, 2, 3, 4, 5};for (int ix = 0; ix < vec.size(); ++ix) {  std::cout << vec[ix];}

Containers provide a different set of operations for element access. For example, the vector provides the operator[], whereas the list does not. The std::list has the front() and back() methods, which return the first and last elements, respectively. The std::vector, as already discussed, additionally provides at() and operator[].

This means that we can't use the preceding loop for iterating list elements. ...

Get Expert C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.