2016-09-17 37 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); });