C++ std:搜索行为或限制
问题描述:
我正在研究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
是否有这种限制,我找不到答案。我很困惑。
答
垃圾值,你会发现,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
寻找的11
,12
,13
任何。我们正在寻找所有的他们,为了。由于它们不是全部存在的(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); });
答
std::search
searches for the first occurrence of a subsequence.(所有b
必须包含在a
的search
找到它)。
因此it
为a.end()
是正常的,因为b
不包含在a
中。
这是不确定的行为取消引用a.end()
,这就是为什么你如果你读了documentation得到4