What’s wrong with the following code? #2

Hello again, fellow programmers! I have stumbled upon an exercise that i must find the wrong thing in the following 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). Any ideas?? i have seen it for about 15 min. and no ideas at all.

1
2
3
4
  vector<int>::iterator iter;
  //increment each score
  for (iter = scores.begin(); iter != scores.end(); ++iter)
      iter++;
"iter" is a pointer .
it points to an "int"
so it doesn't actually increment the int content

you need to do this :
(* iter) ++

it means : "increment where iter points to"
Hint:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>

int main()
{
    // the vector has an even number of elements
    std::vector<int> scores { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;

    // this will print the scores at even positions
    for( auto iter = scores.begin() ; iter != scores.end() ; ++iter )
    {
      std::cout << *iter << '\n' ;
      iter++;
    }

    std::cin.get() ;

    scores.pop_back() ;
    // the vector now has an odd number of elements

    // this will result in undefined behaviour
    for( auto iter = scores.begin() ; iter != scores.end() ; ++iter )
    {
      std::cout << *iter << '\n' ;
      iter++;
    }
}
Ohh, i get it now, thanks guys, by the way, why insert the code at line 16?? Because i didnt comprehend the hint that you, @JLBorges, sent me..
iterators are values that identify a particular element in a container, a way to think about iterators is to imagine them as Post-it notes that you can stick on a specific element in a container. An iterator is not one of the elements! but a way to access one, in order to do that you use the ' * ' symbol.

@Ardeshir81
"iter" is a pointer

No, iterators aren't pointers, but they are so much alike.
Last edited on
> why insert the code at line 16??

Oh, just to make the program wait (after the first loop which has well-defined behaviour), before it goes up in flames when the second loop is executed.
alright i know the theory and got the post that ardeshir made, but i was talking about the hint that JLBorges sent me, i didnt fully comprehend it
> i was talking about the hint that JLBorges sent me, i didnt fully comprehend it

Hint2:
Each time through this loop, the iterator is being incremented two times.
The check iter != scores.end() is made once after every two increments.
What would happen if the sequence contained an odd number of elements?

1
2
3
4
5
    for( auto iter = scores.begin() ; iter != scores.end() ; ++iter /* once */ )
    {
      std::cout << *iter << '\n' ;
      iter++; /* once more */
    }
@JLBorges, that's right, now i get it, thanks!
Topic archived. No new replies allowed.