What is wrong with this code

Feb 27, 2017 at 8:46pm
vector<int>::iterator iter;
// increment each score
for (iter = scores.begin(); iter != scores.end(); ++iter)
{
iter++;
}
Feb 27, 2017 at 8:54pm
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 Python11 or higher standard code you can simplify the above to something like:

1
2
for(auto& itr : scores)
   itr++;

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

Last edited on Feb 27, 2017 at 8:55pm
Feb 27, 2017 at 8:58pm
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.
Feb 28, 2017 at 11:07am
Given the comment above the loop, I guess you want to increment the value and not the iterator: (*iter)++;
Feb 28, 2017 at 2:07pm
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)
{
i++;
}




Last edited on Feb 28, 2017 at 2:08pm
Topic archived. No new replies allowed.