存储unordered_map的位置

时间:2017-01-12 20:41:27

标签: c++ unordered-map

我正在学习C ++并且我尝试制作一个无信息的PlayerInfo图,这是因为我可以将它用作动态内存。我已经到了这个阶段,我正在努力扩展我的知识,并在我的实际项目中使用它。

要做到这一点,我想要一个说GetPlayerPointer(int playerid)的函数;而我想要做的就是返回列表中的位置,这样一段代码就可以做到这一点......更清楚。

??? GetPlayerPointer(int playerid)
{
     auto point = BasicPlayerInfo.find(playerid);
     return point->second;
}

然后这将允许我做类似

的事情
Player = GetPlayerPointer(playerid);
Player.Score = 10;

我至少瞄准这些方面的东西。

我真的很抱歉,并感谢你的帮助。

实际代码:

struct pBasicInfo
{
    bool IsLoggedIn         = false;
    bool Spawned            = false;
    int AdminLevel          = 0;
    std::string PlayerName;
};
extern std::unordered_map<int, pBasicInfo> BasicPlayerInfo;

//CreatePlayer
        pBasicInfo SetupPlayer;
        SetupPlayer.IsLoggedIn = true;
        SetupPlayer.Spawned = false;
        SetupPlayer.PlayerName = GetName(playerid);
        BasicPlayerInfo.insert(std::pair<int, pBasicInfo>(playerid, SetupPlayer));

1 个答案:

答案 0 :(得分:1)

返回引用,但你必须检查对象是否在地图中,如果不是,则执行某些操作:

pBasicInfo &GetPlayer(int playerid)
{
     auto point = BasicPlayerInfo.find(playerid);
     if( point == BasicPlayerInfo.end() )
         throw std::runtime_error( "player not found" );
     return point->second;
}

auto &player = GetPlayer( 123 );
player.Score = 10;

或者您可以返回指针,如果找不到播放器,则返回nullptr,但调用者必须检查:

pBasicInfo *GetPlayerPointer(int playerid)
{
     auto point = BasicPlayerInfo.find(playerid);
     if( point == BasicPlayerInfo.end() )
         return nullptr;
     return &point->second;
}


auto player = GetPlayerPointer( 123 );
if( player ) player->Score = 10;