用 boost::multi_index 管理玩家
(金庆的专栏)
网游服务器上的玩家集合需要多种索引:如用ID查找,角色名查找, 用登录时分配的会话ID查找。
用boost::multi_index进行玩家的管理,可在该容器上建立多种索引。
class Player
{
public:
const PlayerId & GetId() const;
const std::string & GetName() const;
const SessionId & GetSessionId() const;
...
};
typedef boost::shared_ptr<Player> PlayerPtr;
struct tagName {};
typedef boost::multi_index::multi_index_container
<
PlayerPtr,
index_by
<
hashed_unique
<
tag<PlayerId>,
member<Player, PlayerId, &Player::GetId>
>, // hashed_unique
hashed_unique
<
tag<tagName>,
member<Player, std::string, &Player::GetName>
>, // hashed_unique
hashed_unique
<
tag<SessionId>,
member<Player, SessionId, &Player::GetSessionId>
> // hashed_unique
> // index_by
> PlayerSet;
typedef PlayerSet::index<PlayerId>::type PlayerSetById;
typedef PlayerSet::index<tagName>::type PlayerSetByName;
typedef PlayerSet::index<SessionId>::type PlayerSetBySessionId;
使用如:
PlayerSet setPlayers;
PlayerSetById & rSet = setPlayers.get<PlayerId>();
PlayerSetById::const_iterator itr = rSet.find(id);