std :: unordered_map和包含多个元素的键 [英] std::unordered_map and key built of multiple elements
问题描述
我想在包装网络连接的地图对象中存储,其中密钥应为IP地址+端口号。
I'd like to store in map objects wrapping network connections, where key should be IP address + port number.
我的问题是我应该如何处理此类密钥
My question is how should I handle such key with two elements?
我可以定义 std :: unordered_map< std :: pair< std :: string,uint16_t> ;, Connection>
,但是我不确定如何实现它的哈希对象。我只想到天真的实现方式:
I can define std::unordered_map<std::pair<std::string, uint16_t>, Connection>
, but I'm not sure how should I implement hash object for it. Only naive implementation comes to my mind:
std::size_t operator() (const pair<std::string, uint16_t>& key) const
{
std::hash<std::string> ip_hash;
std::hash<uint16_t> port_hash;
return ip_hash (key.first) + port_hash (port.second);
}
我认为简单地将两个哈希值相加是个坏主意。实现散列函数时,我应遵守任何一般规则吗?
I assume that simple addition of two hash values is rather bad idea. Are there any general rules that i should obey to when implementing hash functions?
(我知道我可以根据IP地址和端口号构建一个字符串,但是我我只是好奇)。
(I know, that i can build a string from IP address and port number, but I'm just curious).
推荐答案
一个简单的解决方案是将uint16_t端口号附加到字符串中,以表示IP地址。然后您可以使用 std:unordered_map< string,Connection>
。
A trivial solution will be to append the uint16_t port number to the string, representing the IP address. Then you can use std:unordered_map<string, Connection>
.
这篇关于std :: unordered_map和包含多个元素的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!