2016-09-17 35 views
3

我正在研究std::search(以確定std::set之間是否存在重複項),但我不理解輸出結果。C++ std:搜索行爲或限制

#include <iostream> 
#include <set> 
#include <algorithm> 
using namespace std; 

int main() 
{ 
    set<int> a{9,10,11,12}; 
    set<int> b{11,12,13}; 
    auto it = search(a.begin(), a.end(), b.begin(), b.end()); 

    if (it != a.end()) 
     cout << "Common is " << *it << endl; 
    else 
     cout << "Oops " << *it << endl; 
    return 0; 
} 

因此,我希望*it是11,但事實證明it!=a.end()失敗,*it打印一些無關痛癢的價值(4在這裏),我想我可能會搞砸。

但是,當我將b分配到{11,12}時,一切都按預期工作並打印出"Common is 11"。經過多次嘗試後,我再也看不到這種模式。我不知道std::search是否有這種限制,我找不到答案。我很困惑。

回答

3

垃圾值,你會發現,search()正在尋找一個整個序列

所以在這裏:

set<int> a{9,10,11,12}; 
set<int> b{11,12,13}; 
auto it = search(a.begin(), a.end(), b.begin(), b.end()); 

我們不是在a尋找111213任何。我們正在尋找所有的他們,爲了。由於它們不是全部存在的(a沒有13),所以你得到了a.end()。請注意,取消引用末端迭代器,就像您在Oops案例中做的那樣,是未定義的行爲。

然而,當我分配到b{11,12},一切正常

是的,因爲現在整個序列出現在a


如果你想找到這些單元的任意,只需使用find_if

auto it = find_if(a.begin(), a.end(), [&](int i){ return b.count(i); });