← C++ from Scratch Lesson 60 of 62 · 10 XP

Iterators

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

An iterator is an object that "points" to an item of a container and can move to the next one. It's a generalisation of a pointer: for a vector the iterator is practically a pointer; for a list or a tree it's more complicated, but the interface is the same.

std::vector<int> v = {10, 20, 30};
for (auto it = v.begin(); it != v.end(); ++it)
    std::cout << *it << ' ';            // *it — the item, ++it — the next one
// end() is "past the last one", it mustn't be dereferenced

auto it = std::find(v.begin(), v.end(), 20);   // an iterator to 20, or v.end() if it isn't there
std::distance(v.begin(), it);                  // 1 — the position
for (auto r = v.rbegin(); r != v.rend(); ++r)  // going through backwards

Range-for for (int x : v) is the same loop over begin()…end(), just shorter. Careful: a vector's push_back may move the data, and old iterators become invalid.

Task. Read n numbers into a vector and a number x. Using iterators (no indices), print: the position of the first occurrence of x (or -1), the numbers in reverse order using rbegin/rend, and the sum of the items strictly between the first and the last occurrence of x (or 0 if there are fewer than two occurrences).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.