Iterating containers
A container that is not iterable is analogous to a car that cannot be driven. A container, after all, is a collection of items. The for
loop is one of the most frequent techniques we can use to iterate over container elements:
std::vector<int> vec{1, 2, 3, 4, 5};for (int ix = 0; ix < vec.size(); ++ix) { std::cout << vec[ix] << ", "; }
For element access, containers offer a distinct set of actions. operator[]
, for example, is provided by the vector but not by the list. std::list
has the front()
and back()
methods, which return the first and last elements, respectively. std::vector
, as already discussed, additionally provides at()
and operator[]
.
This means that we cannot use the preceding loop to iterate list elements. However, we can loop over a list (and vector) with a range-based for
loop, as follows:
std::list<double> lst{1.1, 2.2, 3.3, 4.2};for (auto& elem : lst) { std::cout << elem << "...