用 boost::multi_index 管理玩家

本文介绍如何使用Boost库中的multi_index容器来管理网络游戏服务器上的玩家集合,通过为玩家类建立基于ID、角色名和会话ID的三种索引来实现高效查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用 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);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值