使用类/结构体作为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

 

 

 

 

 

 

 

 

posted @ 2012-10-30 16:39    阅读(1775)  评论(0编辑  收藏  举报