First of all, this is NOT homework. I’m using a book I bought for myself to learn the beginning of C++ at home, and it contains an exercise I’m stuck with. It asks me what is wrong with the following code, but I’m not sure if I’m looking it at the right way.
These are the exercise and code:
Assuming that scores is a vector that holds elements of type int,
what’s wrong with the following code snippet (meant to increment each
element)?vector<int>::iterator iter; for (iter = scores.begin(); iter != scores.end(); ++iter) { iter++; }
My guess is that ‘iter++’ is injected in the for function AND the for block, which would mean that it would be injected two times and therefor would pass beyond the end of the loop. Is this correct?
You are correct. The issue with this code is that the iterator is incremented inside the loop, and also after the body of the loop executes.
What the code should do is increment the value stored at the location of the iterator inside the loop, so we need to dereference it.