存储和计数字符串或整数重复项的最佳方法是什么
what is the best way to store and count duplicates of an string or integer?
这段代码解释了我想要做的事情:
unsigned long g_PlayerIP[MAX_AMOUNT_OF_PLAYERS];//save the IP address of each player
int g_max_ip = MAX_CONNECTED_FROM_ONE_IP;
PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid)
{
PlayerLoopList.push_back(playerid);
char szIP[32];
GetPlayerIp(playerid,szIP);//get the ip of the player into szIP
unsigned short explodeIP[4];//declare 4 eight bit variables, to store the exploded ip
sscanf(szIP, " %d[^.].%d[^.].%d[^.].%d", &explodeIP[0], &explodeIP[1], &explodeIP[2], &explodeIP[3]);//explode ip into 4 pats ranging from 0 to 255
g_PlayerIP[playerid] = (explodeIP[0] + (explodeIP[1] << 8) + (explodeIP[2] << 16) + (explodeIP[3] << 24));//store the ip as a 32bit integer
int connected = 0;//variable for counting connected players fron one ip
for(list <int>::iterator i = PlayerLoopList.begin(); i != PlayerLoopList.end(); ++i)
{
if(g_PlayerIP[playerid] == g_PlayerIP[*i])
{
++connected;
}
}
if(connected >= g_max_ip)
{
Report(playerid,IP_FLOOD,g_PlayerIP[playerid]);//too many connected from one ip, report it.
}
return true;
}
看到这个部分:
sscanf(szIP, " %d[^.].%d[^.].%d[^.].%d", &explodeIP[0], &explodeIP[1], &explodeIP[2], &explodeIP[3]);//explode ip into 4 pats ranging from 0 to 255
g_PlayerIP[playerid] = (explodeIP[0] + (explodeIP[1] << 8) + (explodeIP[2] << 16) + (explodeIP[3] << 24));//store the ip as a 32bit integer
int connected = 0;//variable for counting connected players fron one ip
for(list <int>::iterator i = PlayerLoopList.begin(); i != PlayerLoopList.end(); ++i)
{
if(g_PlayerIP[playerid] == g_PlayerIP[*i])
{
++connected;
}
}
这让我有点,嗯,质疑我是否可以更快地完成,c++中必须有一种出色的方法?
只需使用std::map。这样,你就不需要每个可能的ip都有一个,只需要你实际使用的ip。
std::map<int, unsigned int> counts;
counts[playerid]++;
if (counts[playid] >= g_max_ip){ //Report
}
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 派生类销毁的最佳实践是什么
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 在reactor中存储eventHandlers的最佳方式是什么
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将一系列整数放入类的最佳方法是什么?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 在 c++ 中解析数据包数据的最佳方法是什么?
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?