Hiding the Iterator
Other languages let you write for
loops that hide the iterator. C++ can do that, too.
Instead of writing
double total = 0.0;
for (auto p = values.begin(); p != values.end(); ++p) {
total += *p;
}
we can instead say
double total = 0.0;
for (double v : values) {
total += v;
}
Okay, I didn't like this iterator stuff much until now. But I like not having any
*
things anywhere!Well… if we wanted to write to the value to change values in our data structure, we should really make the
double
adouble&
so we have a reference to the original value in the data structure.…
How It Works
When we write
for (TYPE var : thing) {
... var ...
}
C++ basically turns it into
{
auto _past_end = std::end(thing);
for (auto _i = std::begin(thing); _i != _past_end; ++_i) {
TYPE var = *i;
... var ...
}
}
(std::begin
and std::end
call begin()
and end()
member functions on classes, but also “do the right thing” for primitive arrays.)
(When logged in, completion status appears here.)