Iterators in C++


for(iterator t = things.begin(), te = things.end();
    t != te;
    ++t)
{
  ...
}


std::for_each(things.begin(), things.end(), fn);

std::for_each(things.begin(), things.end(), co());
C++ has iterators coming out of its ears with huge chunks of the Standard Library are build around iterators. C++ iterators are commonly described as "pointer-like" - an iterator points to an element in the sequence, you advance the iterator and it points to the next element. Or rather, it points to the where the next element might be.

In the C++ library, an iterator doesn't tell you when its finished or if it can be advanced. Instead, you delimit a sequence with two iterators. One points to the begining, and the other points just past the end. In maths terms this is a half-open range, a useful concept which should probably be more widely known. (Avoids off by one errors for a start.)

Generally used in a for loop. C++ does for_each too, but as a library function rather than as a language feature. Note that you explicitly give it the iterators pointing to the begining and then end, rather than for_each calling some defined interface.