2014-02-10 40 views
4

的尺寸範圍內檢測到的差值雖然做了一些NW編程我偶然發現了以下難題:它是安全調用的std ::等於上可能更短的輸入,如果我知道會有輸入

Im做類似:

static const string my_ip_prefix = "111.222.233"; 

//going through list of IPs where one might have prefix my_ip_prefix 

if (equal(my_ip_prefix .begin(), my_ip_prefix .end(), ip_list[i].begin()))) 
{ 
// 
} 

如果我知道,從ip_list IP地址可以比my_ip_prefix短,但在他們從不同my_ip_prefix在其中至少一個位置這種情況下是安全的呼籲平等的嗎? 例子:它是安全與IP "10.20.30.4"

阿卡做標準規定的順序檢查從前排開始,在std::equalbreak;打電話了嗎?

這似乎明顯,一個是肯定的,但也許ISO PPL想給選項實現並行...

+0

爲什麼不使用'ip_list [I] .compare (0,my_ip_prefix.length(),my_ip_prefix)'? – Chowlett

+0

請注意,一個真正的IPv4地址永遠不會有'.333.',所以你可以用'false'替換你的比較。 –

+0

ups,只是試圖給出不使用實際數據的示例:) – NoSenseEtAl

回答

4

C++ 03 std::equal()需要第二序列至少只要是與第一個。

在C++ 14中,std::equal()有另一個超載,它需要兩個迭代器用於第二個序列。


您應該將IP地址轉換爲uint32_t和比較這些代替,例如:

auto ip_prefix = ::inet_addr("111.222.233.0"); 
auto ip_mask = ::inet_addr("255.255.255.0"); 

bool compare(in_addr_t a, in_addr_t b, in_addr_t mask) { 
    return (a & mask) == (b & mask); 
} 

int main() { 
    std::cout << compare(ip_prefix, ::inet_addr("1.1.1.1"), ip_mask) << '\n'; 
    std::cout << compare(ip_prefix, ::inet_addr("111.222.233.3"), ip_mask) << '\n'; 
} 
+0

...但要求它們與輸入迭代器的距離相同。它似乎(http://en.cppreference.com/w/cpp/algorithm/equal)是C++ 14 – Chowlett

+0

@Chowlett你是對的,沒有期待C++ 14在那裏) –

+0

意見關於uint32_t是錯誤的,因爲我在做is_prefix,除了那個好的A,+1 – NoSenseEtAl

5

如果我們看一下cppreference條目std::equal它說:

[.. 。]其中last2表示first2 +(last1 - first1)

這意味着ip_list[i]將需要至少一樣長。這相當於與draft C++11 standard這部分25.2.11平等說:

template<class InputIterator1, class InputIterator2> 
    bool equal(InputIterator1 first1, InputIterator1 last1, 
      InputIterator2 first2); 

返回:如果對於每個迭代i的範圍在[first1,last1)以下相應條件成立:* I == * (first2 +(I - first1)),[...]

C++14你有版本的,需要一個結束迭代的第二輸入端,相同的截面C++ 11

template<class InputIterator1, class InputIterator2> 
    bool equal(InputIterator1 first1, InputIterator1 last1, 
      InputIterator2 first2, InputIterator2 last2); 

和它說:

如果last1 - first1 = last2 - first2,返回false。 [...]

2

簡單的答案是否定的。不要求按順序完成元素比較。但是,由於您使用的 std::string,它具有隨機訪問迭代器(和 一個size()功能),它的瑣碎先確認是否在 長度足夠:

if (ip_list[i].size() >= my_ip_prefix 
     && std::equal(my_ip_prefix.begin(), my_ip_prefix.end(), ip_list[i].begin())) { 
    // ... 
} 
+0

我知道,但這使得我如果醜陋地獄,因爲它不僅僅是條件...就像在prev評論中提到我剛用boost :: starts_with – NoSenseEtAl

相關問題