0

I'm learning C++ and I've tried making an unordered_map of PlayerInfo, this being because I can use this as dynamic memory. I've gotten to this stage and I'm trying to further my knowledge and use it within my actual project.

To do this I want a function which says GetPlayerPointer(int playerid); and what I want this to do is return the position in the list so a piece of code to make this... well clearer.

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

This then will allow me to do something like

Player = GetPlayerPointer(playerid);
Player.Score = 10;

I'm atleast aiming for something along these lines.

I'm really sorry for asking, and thanks for your help.

Actual Code:

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));
Tom
  • 33
  • 3

1 Answers1

1

return reference, but you have to check if object is in the map and do something if it is not:

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;

or you may return pointer and in case of player not found return nullptr but then caller will have to check:

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;
Slava
  • 43,454
  • 1
  • 47
  • 90
  • Thank you, Slava! Great help and you even taught me something the tutorial never :). – Tom Jan 12 '17 at 21:04