What is the difference between the following two for-loops?
for(int i = 0; i < 5; i++)
{
}
and
for(int i = 0; i < 5;)
{
//End of whatever code to do.
i++;
}
According to http://www.cplusplus.com/doc/tutorial/control/, there shouldn't be a difference. Yet when I run my code (the one below), depending on where the iter++ is, there is a difference.
In this program, I have a separate thread running to get an input. What happens when I move the iter++ to the bottom is that when a separate client connects to the server, I have to enter something into the cin stream before it responds.
When iter++ is at the top inside the for loop, this problem does not happen.
The reason why I want my iter++ to be at the bottom is so that when I receive a disconnect, I can delete the session in my map.
for (iter = network->sessions.begin(); iter != network->sessions.end(); iter++)
{
//bool Deleted = false;
int data_length = network->receiveData(iter->first, network_data);
if (data_length < 0)
{
//no data recieved
continue;
}
if (data_length == 0)
{
printf("Data closed GRACEFULLY LOL \n");
continue;
}
int i = 0;
while (i < (unsigned int)data_length)
{
packet.deserialize(&(network_data[i]));
i += sizeof(Packet);
switch (packet.packet_type) {
case INIT_CONNECTION:
printf("server received init packet from client\n");
char Buffer[100];
//Buffer to hold char values of client id
_itoa_s(client_id - 1, Buffer, 10);
sendActionPackets(client_id - 1, Buffer);
break;
case ACTION_EVENT:
printf("server received action event packet from client\n");
break;
case TALK:
ProcessTalkLine(packet.Message, sizeof(packet.Message), iter->first);
//sendTalkPackets(packet.Message,sizeof(packet.Message), iter->first);
break;
case DISCONNECTING:
printf("I HAVE RECEIVED DC CONNECT /n");
char theMessage[MAX_MESSAGE_SIZE];
sprintf_s(theMessage, "%s has disconnected.", Usernames.find(iter->first)->second.c_str());
Usernames.erase(iter->first);
//network->sessions.erase(iter++);
break;
default:
printf("error in packet types\n");
break;
}
}
}
EDIT: Thanks to @Matt McNabb for pointing out that the continue would...well continue. I've put in my iter++ there as well, but the problem that it would not receive the messages until I put in something remains. If I left the iter++ inside the for loop, this problem isn't there.
network->sessionsis astd::vector, then you can't useeraselike you do in the outcommented line because it will invalidate the iterator.erasereference I linked to in my comment, and see whaterasereturns.