std::search_n查找区间内连续n个满足某一条件或者等于某一值的情况,并返回满足条件的第一个元素位置。
ForwardIterator search_n (ForwardIterator beg, ForwardIterator end,Size count, const T& value);
ForwardIterator search_n (ForwardIterator beg, ForwardIterator end,Size count, const T& value, BinaryPredicate op);
- 第一种形式返回区间内,连续count个元素都等于value的第一个元素的位置。第二种形式返回连续count个元素都使op返回true的第一个元素的位置。如果没有满足条件的情况,两种形式都返回end位置。
- op操作不应改变传入的参数,并且在函数调用状态过程中不能改变op的状态。
- 该函数的第一种形态很好理解,但是第二种形态却有点让人很不舒服。该算法不在早期STL规范中,也没有被严谨对待,因此第二种形式与我们常见的STL算法很不相同,其中op是一个二元谓语(接受两个参数)而不是一元谓语。
直接看下面这个例子:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int>v1{1,1,2,3,4,4,4,5,6,7,8,9};
auto it0 = search_n(v1.begin(), v1.end(), 3, 4);//查找连续三个==4的数
if (it0 != v1.end())
{
cout << distance(v1.begin(), it0)<<endl;
}
//其中search_n的第四个参数对应着lambda表达式中的第二个参数,在这里我们没有实际作用。
auto it1 = search_n(v1.begin(), v1.end(), 3, 0, [](int n, int) {return n > 4;});
if (it1 != v1.end())
{
cout << distance(v1.begin(), it1) << endl;
}
//auto it2 = search_n(v1.begin(), v1.end(), 3, 0, [](int n) {return n > 3;});//错误,编译错误
/*查找连续三个小于5的数,less<T>接受两个参数,如果第一个参数小于第二个则返回true,
否则返回false,通过这里,我们也就明白为什么最开始设计的时候最后一个参数为什么接受两个参数而不是一个参数了。*/
auto it3 = search_n(v1.begin(), v1.end(), 3, 5, less<int>());
if (it3 != v1.end())
{
cout << distance(v1.begin(), it3) << endl;
}
return 0;
}
/*输出结果: 4
7
0
*/