CS 70

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;
}
  • Hedgehog speaking

    Okay, I didn't like this iterator stuff much until now. But I like not having any * things anywhere!

  • LHS Cow speaking

    Well… if we wanted to write to the value to change values in our data structure, we should really make the double a double& so we have a reference to the original value in the data structure.

  • Hedgehog speaking

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.)

What do you think? Nice shorthand, or yet another thing to have to master?

(When logged in, completion status appears here.)