2016-06-10 93 views
0

这的有序表最快的方法就是我遇到的问题:C++:什么是保持IP地址

  1. DNS查询结果中的IP地址的列表,以随机顺序。如果有4个地址,查询2次导致4个地址为 的顺序不同。

  2. 现在需要设置一个可以访问O(1)中地址的有序表。

  3. 潜在的解决方案是每次订购ip地址。因此,如果接收到2,1,7,4,我们可以对它进行排序并且结果总是1,2,4,7,并且通过将ip地址放入向量中,我们可以使用O(1)

  4. 问题出现在DNS结果为5个地址时,可以说新地址是3.现在3将被添加到表格之间,并且由于第三个元素应该是4,因此排序被搞砸了。我们需要添加表格末尾的新元素
  5. 元素的删除也需要适度地处理,具有空表格槽可能会导致问题。

可以这样用O(1)或最坏O(LOGN)

的问题是保持IP的顺序解决每一个有序列表作为输入给出时间

+0

如果你的自定义比较'std :: set',它被排序并且查找惩罚为O(log n)? – Arunmu

+0

谢谢..什么应该是比较?如果元素是新的而不存在于集合中? – Nikhil

+1

我所见过的DNS数据包中返回的IP地址数量最多(并且我在撰写DNS测试软件五年)时间在二十多年。你使用哪种极其有限的环境,哪些项目的O(1)和O(n * log n)之间的差异甚至可以衡量? –

回答

0

有所作为喜欢这个?

#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}); 
}