std::map和id不断递增
std::map and id's that keep incrementing
我正在从事客户端和服务器项目。
有一个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);
}
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 使用一个考虑到std::map中键值的滚动或换行的键
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 允许从 std::map 的密钥窃取资源?
- 从函数角度看ID到文件路径的内部与外部映射
- 通过组合不同的类型来创建唯一的id
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- FFMPEG配置文件级别id大小无效
- 方法内部但循环仍得到预期的不合格id错误C++
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 如何获取 GLFW 窗口 ID?
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 当简单捕获中的标识符显示为参数的声明符 ID 时,没有编译器诊断
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- std::map和id不断递增
- c++:std::map数字id的迭代排序-交叉编译器