find_first_of是怎么样一个执行过程?
while((it = find_first_of(it, a.end(),b.begin(),b.end())) != a.end())
{
++ cnt;++ it;
}
这是C++ primer上的例子,看了半天还是没太懂。
我简单说下我的理解,大家帮忙看看。
第一次循环, 遍历b容器,看是否与迭代器 it 指向的元素相同,如果有,则返回值还是原来的it,如果没有it自增,继续遍历b容器,如果有,则返回值新的it……cnt自增,it再自增,指向下一个元素
然后第二次循环,如上所示。
书上原话是这样的:
1.在第一段范围内查找与第二段范围中人气元素匹配的元素,然后返回一个迭代器,指向第一个匹配的元素。
2.调用find first of查找b中的每个元素是否与第一个范围内的元素匹配,也就是在it到a.end()范围内查找一个元素。该函数返回此范围内第一个同时存在于第二个范围中的元素。
3.在while的第一次循环中,遍历整个a范围。第二次以及后续的循环迭代则只考虑a中尚未匹配的部分。
好吧,我感觉我的理解 跟 书上完全不同。。.
那位大神 能告诉我find first of 函数执行的 具体过程, 话说我看不懂汇编,别让我自己反推 - -!..
[解决办法]
- C/C++ code
template<class ForwardIterator1, class ForwardIterator2> ForwardIterator1 find_first_of ( ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2){ for ( ; first1 != last1; ++first1 ) for (ForwardIterator2 it=first2; it!=last2; ++it) if (*it==*first1) // or: if (comp(*it,*first)) for the pred version return first1; return last1;}
[解决办法]
find_first_of 在前两个迭代器中查找后两个迭代器的序列. 成功, 返回查找到的位置, 失败返回 end.
所以 find_first_of(it, a.end(),b.begin(),b.end()) 就是在 a 容器从 it 开始的地方开始查找 b 容器中的元素. 如果没找到, 返回 a.end(), 整个 while 结束.
如果找到了, 返回找到的位置, 然后从这个位置的下一个位置再次查找.
所以, cnt 最终表示 a 中出现 b 的次数.
[解决办法]
Searches for the first occurrence of any of several values within a target range or for the first occurrence of any of several elements that are equivalent in a sense specified by a binary predicate to a specified set of the elements.
template<class ForwardIterator1, class ForwardIterator2>
ForwardIterator1 find_first_of(
ForwardIterator1 _First1,
ForwardIterator1 _Last1,
ForwardIterator2 _First2,
ForwardIterator2 _Last2
);
template<class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
ForwardIterator1 find_first_of(
ForwardIterator1 _First1,
ForwardIterator1 _Last1,
ForwardIterator2 _First2,
ForwardIterator2 _Last2,
BinaryPredicate _Comp
);
Parameters
_First1
A forward iterator addressing the position of the first element in the range to be searched.
_Last1
A forward iterator addressing the position one past the final element in the range to be searched.
_First2
A forward iterator addressing the position of the first element in the range to be matched.
_Last2
A forward iterator addressing the position one past the final element in the range to be matched.
_Comp
User-defined predicate function object that defines the condition to be satisfied if two elements are to be taken as equivalent. A binary predicate takes two arguments and returns true when satisfied and false when not satisfied.
vs2008 的msdn