std::vector<int> vbegin()end()v[0]v[1]v[2]v[3]v[4]$ ./iter26 25bendeint sumauto n1#include <algorithm>2#include <iostream>3#include <vector>4int main() {5 std::vector<int> v{5, 2, 8, 2, 9};6 auto b = v.begin(), e = v.end();7 int sum = 0;8 for (auto it = b; it != e; ++it)9 sum += *it;10 auto p = std::find(b, e, 8);11 std::sort(b, e);12 auto n = std::count(b, e, 2);13 std::cout << sum << ' ' << n << '\n';14 std::cout << *p << '\n';15}52829552829+1+12625it!pp???
Violet card: the code (iter.cpp)Slate cells: the vector's elements; dashed: the end slot; rose markers: iterators; khaki: sum and nTokens: the iterator it walking, values moving, red ! and ? for misuseIn front: the code card iter.cpp. Behind it: the vector v as five memory cells and a dashed slot just past the end, with the iterator markers b and e in front of the row. On the right: sum and n; at the back: the output screen. The iterator it reads a value and steps on; the loop walks it from b to e and adds every value into sum. std::find, std::sort and std::count each take the range [b, e): find leaves p on the 8, sort moves the values while p stays put, and count counts the 2s. The program prints 26 2 and 5, and a push_back that needs a bigger block invalidates b, e and p.

Iterators

  1. std::vector<int> v{5, 2, 8, 2, 9}; stores five ints side by side in one block of memory. We will walk along this row without using indexes at all. The tool for that is an iterator.

Algorithms

Run it, and a trap

What happens

;; step 1/10 · vector
5  std::vector<int> v{5, 2, 8, 2, 9};
   v[0] v[1] v[2] v[3] v[4]
    5    2    8    2    9
   one block of memory, no gaps
   v.size() == 5

end() is a position, not an element: reading *v.end() is undefined behaviour. Because ranges are half-open, an empty range is simply b == e, and the number of elements is e - b. Each algorithm says which iterators it needs. std::find only reads forward, so it works on every container. std::sort needs random-access iterators, so std::sort on a std::list does not compile; a list has its own l.sort().