使用类/结构体作为boost::unordered_map中的key时需要实现hash_value函数

有如下结构体:

 1 typedef struct _client_msg
 2 {
 3     _client_msg(int clientID, int msgValue)
 4     {
 5         this->clientID = clientID;
 6         this->msgValue = msgValue;
 7     }
 8 
 9     int clientID;
10     int msgValue;
11 }CLIENT_MSG;

使用它作为boost::unordered_map的key:

typedef boost::unordered_map<CLIENT_MSG, int>  MSG_MAP;

编译时报错:

......error: no matching function for call to ‘hash_value(const _client_msg&)......

 经查:在该类所在的namespce中,需要实现hash_value函数,因为unordered_map内部在插入数据时需要调用该函数。我的实现如下:

1 std::size_t hash_value(const CLIENT_MSG& o)
2 {
3     std::size_t seed = 0;
4     boost::hash_combine( seed, o.clientID);
5     boost::hash_combine( seed, o.msgValue);
6     return seed;
7 }

同时还需要实现的有运算符“== ”:

1     bool _client_msg::operator ==(const _client_msg& o) const
2     {
3         return (clientID == o.clientID) && (msgValue == o.msgValue);
4     }

而运算符"<"反倒不需要实现。这也许跟unordered_map的内部实现有关,有时间再研究。

 

http://stackoverflow.com/questions/3611951/building-an-unordered-map-with-tuples-as-keys

http://www.boost.org/doc/libs/1_38_0/doc/html/hash/custom.html

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/chutianyao/archive/2012/10/30/2746593.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值