Last active
March 30, 2020 16:38
-
-
Save iaoedsz2008/54bd7bf2f7d9a839c3ef47942af44d58 to your computer and use it in GitHub Desktop.
std::unordered_map 自定义key类型
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// hash 函数 | |
struct sockaddr_in_hash | |
{ | |
size_t operator()(const sockaddr_in &addr) const | |
{ | |
return *(size_t*)&(addr.sin_addr); | |
} | |
}; | |
// 每次查找时最少调用一次,hash值相同时可能调用2次或更多次. | |
struct sockaddr_in_compare //比较函数 == | |
{ | |
bool operator()(const sockaddr_in &addr1, const sockaddr_in &addr2) const | |
{ | |
return memcmp(&addr1, &addr2, sizeof(sockaddr_in)) == 0; | |
} | |
}; | |
// hash 函数 | |
struct sockaddr_in6_hash | |
{ | |
size_t operator()(const sockaddr_in6 &addr) const | |
{ | |
return *(size_t*)&(addr.sin6_addr); | |
} | |
}; | |
// 每次查找时最少调用一次,hash值相同时可能调用2次或更多次. | |
struct sockaddr_in6_compare | |
{ | |
bool operator()(const sockaddr_in6 &addr1, const sockaddr_in6 &addr2) const | |
{ | |
return memcmp(&addr1, &addr2, sizeof(sockaddr_in6)) == 0; | |
} | |
}; | |
typedef std::unordered_map<sockaddr_in, uint64_t,sockaddr_in_hash, sockaddr_in_compare> IPv4_map; | |
typedef std::unordered_map<sockaddr_in6, uint64_t,sockaddr_in6_hash, sockaddr_in6_compare> IPv6_map; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment