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++;
#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++;
}
}
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.
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.
> 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 */
}