can anyone identify the error in the following code?

1
2
3
4
5
6
vector<int>::iterator iter;
//increment each score
for (iter = scores.begin(); iter != scores.end(); ++iter)
{
iter++;
}
You are incrementing iter twice, which means that (in some cases), iter can increment past the final element in the vector.

Take this example code for instance:

1
2
3
4
5
for(int i=0; i <= 10; ++i)
{
  i++;
  cout << i << endl;
}


Output:

1
3
5
7
9
11


As you can see, since the value of i is checked before the loop is executed, it is possible for it to be greater than the maximum value.

Here is another example that shows the problem with an array:

1
2
3
4
5
6
7
int array[5] = {1, 1, 1, 1, 1};

for(int i=0; i < 5; ++i)
{
  i++;
  cout << array[i] << endl;
}


My output:

1
1
32767


Why is the 3rd number garbage? Because it isn't part of the array.

The first number outputted is array[1], then array[3], then array[5] which doesn't exist.
basically the array cannot increment by 2?
To summarise georgep,

iter++; and ++iter; moves the iterator to the next value in the array.

(*iter)++; increases what the iterator is pointing at.

Very, very different.
Last edited on
Oh, I didn't realise that that was what Yangfizz was trying to do.
It's just a guess; Yangfizz hasn't stated what she's actually trying to do.
it's a problem i read from a book lol.
just started learning cpp a week ago.
Topic archived. No new replies allowed.