有所作为喜欢这个?
#include <unordered_map>
#include <array>
#include <algorithm>
#include <initializer_list>
#include <cassert>
struct ip_address
{
ip_address(std::initializer_list<std::uint8_t> il)
{
auto max = std::min(il.size(),_ip4_data.size());
assert(max == 4);
std::copy_n(il.begin(), max, _ip4_data.begin());
}
auto& data() const { return _ip4_data; }
auto& data() { return _ip4_data; }
const uint8_t& operator[](std::size_t i) const {
return _ip4_data[i];
}
std::array<std::uint8_t, 4> _ip4_data;
};
bool operator==(const ip_address& l, const ip_address& r)
{
return l.data() == r.data();
}
namespace std
{
template<> struct hash<ip_address> {
std::size_t operator()(const ip_address& r) const
{
// reverse the byte order so that the lsb of the ip
// has the greatest effect on the hash value
return std::size_t((r[3] << 24) & 0xff000000
+ (r[2] << 16) & 0x00ff0000
+ (r[1] << 8) & 0x0000ff00
+ r[0] & 0x000000ff);
}
};
}
using client_server_map = std::unordered_map<ip_address, ip_address>;
int main()
{
client_server_map cs_map;
cs_map.emplace(ip_address{10, 0, 0, 1}, ip_address{192, 168, 0, 1});
cs_map.emplace(ip_address{10, 0, 0, 2}, ip_address{192, 168, 0, 2});
cs_map.erase(ip_address{10, 0, 0, 1});
}
如果你的自定义比较'std :: set',它被排序并且查找惩罚为O(log n)? – Arunmu
谢谢..什么应该是比较?如果元素是新的而不存在于集合中? – Nikhil
我所见过的DNS数据包中返回的IP地址数量最多(并且我在撰写DNS测试软件五年)时间在二十多年。你使用哪种极其有限的环境,哪些项目的O(1)和O(n * log n)之间的差异甚至可以衡量? –