I am very curious to learn why the below code does not run in a continuous loop. And I’m also looking for some ways to achieve what I want to achieve–which is resetting a loop inside of the loop. I need to do this because I need to account for each element in a container. The reason why this is because I might start off in the middle, and need to loop back around to check the others / and need to recheck other information too. So on with my little test example:
for ( int i = 0; i != 10; i++ ) {
std::cout << std::endl << "TEST: " << i << std::endl;
if ( i++ == 10 ) {
i = 0;
} else {
i--;
}
}
Is there any particular reason why the above does not work? I am very interested in knowing why, so I can learn how everything works. This also leads into a much bigger problem I am facing. Which is the below code. I am using MSVC++ 2010 Express. Also, this is one thread, so other data is not accessing it. It is an unordered_map using STL. its size if 2 (i checked).
for (game_player_client_map::const_iterator it = gpc_map_ptr->begin(); it != gpc_map_ptr->end(); ++it) {
if ( it++ == gpc_map_ptr->end() ) {
cout << endl << "IT == gpc_map_ptr->end()" << endl;
it = gpc_map_ptr->begin();
} else {
it--;
}
}
I appreciate any feedback SO has to offer, and any new things to learn 🙂 If further information is needed I will provide. Thank you for your time.
Because the condition is checked before the body of the loop is entered. When
i == 10, the loop is broken, before your code can execute at the time thati++would evaluate to 10.Remember that postincrement increments the variable and returns the old value. So if
iis 9,i++evaluates to 9 also, but the next time you usei, it will be 10.If you want the variable to be incremented and use the new value in an expression, use preincrement:
You could completely ditch the increment however, and just use
i + 1. That way you don’t have to de-incrementiin theelseblock.Your misunderstanding of postincrement is probably also the source of the bug in the second block of code you posted. You can change it to preincrement, or if
itis a random-access iterator, you can do the same thing as mentioned above and check ifit + 1 == gpc_map_ptr->end()and not have to de-incrementitin theelseblock.