C++STL算法篇adjacent_find搜寻满足条件的两个连续元素算法

adjacent_find(beg,end)和adjacent_find(beg,end,op)的特点

1:迭代器类型:输入迭代器
2:无op版本,返回区间[beg,end)中首个连续两次出现元素的首元素位置
3:有op版本,返回区间[beg,end)中首个连续两个元素使得op(elem,nextelem)为真的首元素的位置
4:如果未找到两者都返回true

#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
	//寻找c1首次连续出现两次的元素的第一个元素
	vector<int>c1 = { 1,2,1,4,4,5,6,7,7,8,9 };

	auto it = adjacent_find(c1.begin(), c1.end());

	 if (it != c1.end())
		 //返回满足条件的元素距离首部的距离
		 cout << distance(c1.begin(),it)+1<< endl; 
	 else
		 cout << "未发现" << endl;


}
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
	//寻找c1中首次连续两个元素的满足op为true,即寻找(a,4a) 返回a的位置
	vector<int>c1 = { 1,2,1,4,4,5,6,7,7,8,9 };

	auto it = adjacent_find(c1.begin(), c1.end(), 
	[](int i, int j)->bool { return (i * 4) == j; });

	 if (it != c1.end())
		 //返回满足条件的元素距离首部的距离
		 cout << distance(c1.begin(),it)+1<< endl; 
	 else
		 cout << "未发现" << endl;


}
原创文章 23 获赞 1 访问量 352

猜你喜欢

转载自blog.csdn.net/weixin_44806268/article/details/105835535