存储和计算字符串或整数的重复项的最佳方法是什么?

时间:2012-07-13 01:09:55

标签: c++

此代码解释了我想要做的事情:

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 ++中必须有一种极好的方式?

1 个答案:

答案 0 :(得分:5)

只需使用std :: map。这样你就不需要每个可能的ip,只有你实际使用的ips。

std::map<int, unsigned int> counts;

counts[playerid]++;
if (counts[playid] >= g_max_ip){ //Report
}