C++STL算法篇find_first_of搜寻某元素第一次出现算法

find_first_of(beg,end,sbeg,send)和find_first_of(beg,end,sbeg,send,op)的特点

1:无op版本,返回同时在区间[beg,end)和[sbeg,send)出现的第一个元素位置的迭代器,同时我们可以采用逆向迭代器获得最后一个元素,未发现则end
2:有op版本,返回区间[beg,end)中第一个能与[sbeg,send)内其中一个元素使得op(elem,selem)为真的元素位置的迭代器,未发现则end
3:op不应该改动传入的参数以及自身的状态
4:迭代器类型:前向迭代器

#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
	//寻找第一个同时在c1,c2出现的元素
	vector<int>c1 = { 1,2,3,4,5,6,7,8,9 };
	vector<int>c2 = {3,4,5,6,7};

	auto it = find_first_of(c1.begin(), c1.end(), c2.begin(), c2.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,c2出现的元素
	vector<int>c1 = { 1,2,3,4,5,6,7,8,9 };
	vector<int>c2 = {3,4,5,6,7};

	auto it = find_first_of(c1.rbegin(), c1.rend(), c2.begin(), c2.end());

	 if (it != c1.rend())
	     //返回满足条件的元素距离首部的距离
		 cout << distance(c1.begin(),it.base())<< endl;
	 else
		 cout << "未发现" << endl;
}
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
	//寻找第一个c1中出现,并内与c2其中一个元素使得op返回真的元素,即第一个大于5的元素位置
	vector<int>c1 = { 1,2,3,4,5,6,7,8,9 };
	vector<int>c2 = {7,5,6};

	auto it = find_first_of(c1.begin(), c1.end(), c2.begin(), c2.end(),greater<int>());

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

**op推荐采用lambdas表达式:lambdas的使用方法
**

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值