What is wrong with this code

vector<int>::iterator iter;
// increment each score
for (iter = scores.begin(); iter != scores.end(); ++iter)
What do you think iter++ is doing in the loop body? Hint: look at the loop increment section (++itr) does anything look similar? You need to realize that an iterator has similarities to a pointer. When you increment the non-dereferenced iterator you're incrementing the iterator not modifying the values the iterator is pointing to.

By the way if you're using C++11 or higher standard code you can simplify the above to something like:

for(auto& itr : scores)

Which should increase the value held in each element of your vector.
you increment iter twice for some reason. That may or may not be wrong, depending on what you are doing exactly.

Last edited on
Assuming that you define vector<int> scores and put this in a program, it compiles and runs.

Whether something is "wrong" with it depends on what it's supposed to do. One odd thing is that it increments the iterator twice: once as the last part of the for() statement and once inside the body of the loop.
Given the comment above the loop, I guess you want to increment the value and not the iterator: (*iter)++;
let assume score.size() == 1
++iter and iter++; will be executed and you misses the end().
safe practice:
for (i= 0; iter < scores.size(); ++i)

Last edited on
Topic archived. No new replies allowed.