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?
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?
(I know, that i can build a string from IP address and port number, but I'm just curious).
ip_hashandport_hash. Especially the latter -- a port number can serve excellently as its own hash (i.e. hash == identity). If you don't expect many connections from the same IP address you can even take the port out of the equation entirely.