简体   繁体   中英

Which datatype should I use?

I'm really new to C++ and I'm having a confusion over something. What I've achieved so far is:

  • Created a class named CPlayer

What I want to do next is:

  • Create a datatype (array/map/or whatever) to store the CPlayer in for each individual player. (PS: Each player can have an entirely different ID from the other player, for example: player1 has ID 1, player2 has ID 5)

In Squirrel I could do:

local playerInfo = {}; // Create a table
playerInfo[ playerId ]      <-  CPlayer();
// To remove it -
playerInfo.rawdelete( playerId );

Not sure what would be best in C++ to reproduce this.

Having just looked up what a table is in Squirrel, and from reading the question above it seems the C++ version of what you want is

#include <map>

std::map<int, CPlayer> playerInfo;

The equivalent of playerInfo[ playerId ] <- CPlayer(); would be

playerInfo[playerId] = CPlayer();

and the equivalent of playerInfo.rawdelete( playerId ); would be

playerInfo.erase(playerId);

More information here

You can use std::map as shown below. Below sample should give fair idea on the usage.

std::map<into, PlayersInfo> mapPlayerInfo:
int nPlayerId1 = 1; // Player 1 Id sample
int nPlayerId2 = 2; // Player 2 Id sample

PlayerInfo player1(nPlayerId1,...); // Additional arguments to constructor if required
mapPlayerInfo[nPlayerId1] = player1;

PlayerInfo player2(nPlayerId2,...); // Sample 2
mapPlayerInfo[nPlayerId2] = player2;

//Deleting based on player Id
mapPlayerInfo.erase(nPlayerId1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM