std::map和id不断递增

std::map and id's that keep incrementing

本文关键字:id map std      更新时间:2023-10-16

我正在从事客户端和服务器项目。

有一个std ::所有会话的地图,看起来有点像这样:

std::map<int, SOCKET> Sessions;
int g_TotalClientCount;
void Server::HandleNewClientConnection(SOCKET clientSocket){
    Sessions.insert(pair<int, SOCKET>(g_TotalClientCount, clientSocket));
    g_TotalClientCount++;
}
/*Something similar on disconnect*/
void Server::KickClient(int clientId){
    SendPacket(...)
    Sessions.erase(clientId);
}

假设,随着时间的流逝,g_totalclientcount变得非常高,最终会超过max_int(最终导致错误/崩溃(。

是否有正确的方法可以在地图中删除和插入项目,还可以将G_TotalClientCount保留到实际连接的实际用户数量而不是连接的用户数量中?使用

g_TotalClientCount--;

最终会引起重复。

g_totalclientcount仅在HandleneWclientConnection部分中使用。

我知道我可能永远不会有一个实际问题,但是我想知道这样做的正确方法。

更适合您的问题将是std::set(对数复杂性(或更好的是std::unordered_set(恒定时间复杂性(。您可以将insert方法返回的iterator用作clientId

C 98:

#include <set>
std::set<SOCKET> Sessions;
std::set<SOCKET>::iterator Server::HandleNewClientConnection(SOCKET clientSocket) {
    std::pair<std::unordered_set<SOCKET>::iterator, bool> inserted =
        Sessions.insert(clientSocket);
    if (!inserted.second) {
        // handle the insertion error
    }
    return inserted.first;
}
void Server::KickClient(std::set<SOCKET>::iterator clientId){
    SendPacket(...)
    Sessions.erase(clientId);
}

C 11 :

#include <unordered_set>
std::unordered_set<SOCKET> Sessions;
auto Server::HandleNewClientConnection(SOCKET clientSocket) {
    auto inserted = Sessions.insert(clientSocket);
    if (!inserted.second) {
        // handle the insertion error
    }
    return inserted.first;
}
void Server::KickClient(std::unordered_set<SOCKET>::iterator clientId){
    SendPacket(...)
    Sessions.erase(clientId);
}

C 17:

#include <unordered_set>
std::unordered_set<SOCKET> Sessions;
auto Server::HandleNewClientConnection(SOCKET clientSocket) {
    auto [iterator, success] = Sessions.insert(clientSocket);
    if (!success) {
        // handle the insertion error
    }
    return iterator;
}
void Server::KickClient(std::unordered_set<SOCKET>::iterator clientId){
    SendPacket(...)
    Sessions.erase(clientId);
}