0

This is my loop;

for (sf::TcpSocket &client : clients)
{
    ...
}

In the loop, I would like to check if someone has disconnected, and if so, remove them from the list of users, I just don't know how to check which user it is up to in the list.

The list of users is a vector of 100 sf::tcpsockets in the loop if someone has disconnected I just skip the rest of the code with a continue statement.

I check if they have disconnected by sending "ping" over and if no response is given, then they disconnected.

There is one list of users, that being named clients

1 Answers1

1

Range based for loops are not supposed to be for modification of the container itself. If you wish to add or remove elements from the container, you should use a standard for loop:

for (auto it = std::begin(clients); it != std::end(clients);)
{
    sf::TcpSocket& client = *it;
    // accept data from the client socket

    if (acceptStatus == sf::Socket::Disconnected)
    {
        it = clients.erase(it);
        erased = true;
    }
    else
    {
        ++it;
    }
}

Notice that the iterator is not incremented as part of the for loop post condition. If we did this, when an element is erased the iterator will be incremented which is not what you want because you will accidentally skip an element.

Gambit
  • 954
  • 9
  • 15