C++STL算法篇之search、search_n、find_end搜寻区间算法

search_n(beg,end,count,value)和search_n(beg,end,count,value,op)的特点

1:迭代器类型:输入迭代器
2:无op版本返回指向区间[beg,end)中第一组连续count个与value值相同的元素区间的首元素位置的迭代器,未发现则返回end
3:有op版本返回指向区间[beg,end)中第一组连续count个让op(elem,value)为true的元素区间的首元素位置的迭代器,未发现则返回end

//无op版本,寻找区间中连续两个值为3
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
	vector<int>c1 = { 1,2,3,3,4,5,3,3,6,7,8,9 };
	auto it = search_n(c1.begin(),c1.end(),2,3);
	 if (it != c1.end())
	     //返回满足条件区间首元素距离首部的距离
		 cout << distance(c1.begin(),it)+1<< endl;
	 else
		 cout << "未发现" << endl;
}
//有op版本,寻找区间中连续两个大于3的元素区间,返回其首元素与首部的距离
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
	vector<int>c1 = { 1,2,3,3,4,5,3,3,6,7,8,9 };
	auto it = search_n(c1.begin(),c1.end(),2,3,greater<int>());
	 if (it != c1.end())
	  //返回满足条件区间首元素距离首部的距离
		 cout << distance(c1.begin(),it)+1<< endl; 
	 else
		 cout << "未发现" << endl;
}

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

1:迭代器类型:前向迭代器
*2:无op版本,返回区间[beg,end)中和[sbeg,send)完全符合的元素区间的第一元素位置迭代器,未发现则返回end.
3:有op版本,返回区间[beg,end)中和[sbeg,send)中对应元素使op(elem,selem)都为true的元素区间的首元素位置的迭代器,未发现则返回end.
4:op不应该变动传入的参数

//无op版本
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
	//寻找c1序列中 {6,7,8}首次出现的元素区间
	vector<int>c1 = { 1,3,3,3,4,5,3,3,6,7,8,9 };
	vector<int>c2 = {6,7,8};
	auto it = search(c1.begin(), c1.end(), c2.begin(), c2.end());
	 if (it != c1.end())
		 cout << distance(c1.begin(),it)+1<< endl; //返回满足条件区间首元素距离首部的距离
	 else
		 cout << "未发现" << endl;
}

//有op版本
#include<iostream>
#include<vector>
#include<functional>
using namespace std;
struct check
{
	bool operator()(int i, bool j)
	{
		if (j)  //j=1代表我要偶数
		{
			return (i % 2) == 0;
		}
		else
		{
			return (i % 2) == 1;
		}
	}
};
int main()
{
	//寻找c1序列中 {偶数,奇数,偶数}第一次出现的元素区间
	vector<int>c1 = { 1,3,3,3,4,5,3,3,6,7,8,9 };
	vector<bool>c2 = {1,0,1};
	auto it = search(c1.begin(), c1.end(), c2.begin(), c2.end(),check() );
	 if (it != c1.end())
	 //返回满足条件区间首元素距离首部的距离
		 cout << distance(c1.begin(),it)+1<< endl; 
	 else
		 cout << "未发现" << endl;
}

find_end 函数本应该叫serach_end

功能:与serach 一样,不过返回的是最后一个满足条件的元素区间的首元素位置迭代器

原创文章 23 获赞 1 访问量 354

猜你喜欢

转载自blog.csdn.net/weixin_44806268/article/details/105782757
今日推荐