Loading lessons...
Iterators
Iterators
An iterator is an object that stands at one element of a container and can move to the next one. It gives one uniform way to walk through a vector, a list, or a map, no matter how those containers store data inside.
begin() and end()
std::vector<int> v = {10, 20, 30};
auto it = v.begin(); // points at the first element
v.begin()returns an iterator to the first element.v.end()returns the marker one past the last element. It is the stop line for loops.
Read with *, move with ++
std::cout << *it; // 10, the value it points to
++it; // advance to the next element
std::cout << *it; // 20
The star dereferences the iterator to get the element. The ++ operator steps it to the next element.
The classic loop
for (auto it = v.begin(); it != v.end(); ++it) {
std::cout << *it << "\n";
}
It starts at begin(), keeps going while it != end(), and advances each trip with ++.
Why not just indexes?
For a basic vector you could count with 0, 1, 2. But a map has no index - the whole idea is walking from key to key. And every algorithm in the library accepts the same [begin, end) pair. Learn the iterator once and one pattern works everywhere.
TL;DR
- An iterator points at one element and can step to the next.
begin()andend()fence the collection;end()is one past the last.*itreads the value;++itwalks on.- Loop while
it != v.end()and you will never run past the end. - Range-loops and
<algorithm>both build on iterators.