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};
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;
}
Is this version okay?
for (size_t i = 0; i < fibs.size(); ++i) { fibs[i] = fibs[i] + fibs[i]; }
Sorry, no.
std::list
doesn't haveoperator[]
. But your code would work if we'd been usingstd::vector
.You also used
operator[]
three times when you could have just used it once.
Optional Extra
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?The
end()
member function is constant time, so it won't make any difference to the asymptotic performance.And
end()
is usually coded so it's really efficient, so the cost of calling it multiple times is negligible.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;
}
Meh.
Exactly.
(When logged in, completion status appears here.)