CS 70

Before You Start

Suppose I have a list of numbers, defined as

std::list<int> fibs{1,1,2,3,5,8,13,21,34,55,89};

Write a code snippet that doubles every value in the list.

Here are a few options that would work:

for (std::list<int>::iterator iter = fibs.begin(); iter != fibs.end(); ++iter) {
    *iter *= 2;
}
for (auto iter = fibs.begin(); iter != fibs.end(); ++iter) {
    *iter *= 2;
}
for (int& v : fibs) {
    v *= 2;
}
  • Dog speaking

    Is this version okay?

    for (size_t i = 0; i < fibs.size(); ++i) {
        fibs[i] = fibs[i] + fibs[i];
    }
    
  • LHS Cow speaking

    Sorry, no. std::list doesn't have operator[]. But your code would work if we'd been using std::vector.

  • Rabbit speaking

    You also used operator[] three times when you could have just used it once.

Optional Extra

  • Duck speaking

    I've noticed that in the explicit versions, we call fibs.end() each time we go around the loop. Is that okay? Wouldn't it be inefficient?

  • LHS Cow speaking

    The end() member function is constant time, so it won't make any difference to the asymptotic performance.

  • RHS Cow speaking

    And end() is usually coded so it's really efficient, so the cost of calling it multiple times is negligible.

  • LHS Cow speaking

    But if you really wanted, you could put the value in a variable instead.

You may see some people write their code to use an extra variable and avoid an extra end() call. For example,

for (auto iter = fibs.begin(), endpt = fibs.end(); iter != endpt; ++iter) {
    *iter *= 2;
}
  • Goat speaking

    Meh.

  • LHS Cow speaking

    Exactly.

(When logged in, completion status appears here.)