用 boost::multi_index 管理玩家
(金庆的专栏)
网游服务器上的玩家集合需要多种索引:如用ID查找,角色名查找, 用登录时分配的会话ID查找。
用boost::multi_index进行玩家的管理,可在该容器上建立多种索引。
1 class Player
2 {
3 public:
4 const PlayerId & GetId() const;
5 const std::string & GetName() const;
6 const SessionId & GetSessionId() const;
7
8 };
9
10 typedef boost::shared_ptr<Player> PlayerPtr;
11
12 struct tagName {};
13
14 typedef boost::multi_index::multi_index_container
15 <
16 PlayerPtr,
17 index_by
18 <
19 hashed_unique
20 <
21 tag<PlayerId>,
22 member<Player, PlayerId, &Player::GetId>
23 >, // hashed_unique
24
25 hashed_unique
26 <
27 tag<tagName>,
28 member<Player, std::string, &Player::GetName>
29 >, // hashed_unique
30
31 hashed_unique
32 <
33 tag<SessionId>,
34 member<Player, SessionId, &Player::GetSessionId>
35 > // hashed_unique
36 > // index_by
37 > PlayerSet;
38
39 typedef PlayerSet::index<PlayerId>::type PlayerSetById;
40 typedef PlayerSet::index<tagName>::type PlayerSetByName;
41 typedef PlayerSet::index<SessionId>::type PlayerSetBySessionId;
42 使用如:
PlayerSet setPlayers;
PlayerSetById & rSet = setPlayers.get<PlayerId>();
PlayerSetById::const_iterator itr = rSet.find(id);