C++标注库---find()&find_if()&search_n()

搜索元素

如果要搜索第一个匹配的元素,你可能要用到:

find(beg,end,value)

find_if(beg,end,op)

第一个形式返回区间[beg,end)中第一个“元素值等于value”的元素的位置;

第二个形式返回区间[beg,end)中令以下一元判断式结果为true的第一个元素:op(elem)

如果没有找到匹配元素,两种都返回end。


关联式容器(set,map,multiset,multimap)提供了一个等效的成员函数find(),拥有对数复杂度,而非线性复杂度。


代码示例:

//find
#include"fuzhu.h"

using namespace std;

int main()
{
	list<int> coll;

	INSERT_ELEMENTS(coll,1,9);
	INSERT_ELEMENTS(coll,1,9);

	PRINT_ELEMENTS(coll,"coll:");

	list<int>::iterator pos1;

	pos1=find(coll.begin(),coll.end(),4);//查找第一次出现4的元素,返回值的是位置

	list<int>::iterator pos2;

	if(pos1!=coll.end())
	{
		pos2=find(++pos1,coll.end(),4);
	}

	if(pos1!=coll.end()&&pos2!=coll.end())
	{
		for_each(--pos1,++pos2,print);//[beg,end)
		cout<<endl;
	}

	system("pause");
	return 0;
}

运行结果:

4 5 6 7 8 9 1 2 3 4


//find_if
#include"fuzhu.h"

using namespace std;

int main()
{
	vector<int> coll;
	vector<int>::iterator pos;

	INSERT_ELEMENTS(coll,1,9);

	PRINT_ELEMENTS(coll,"coll: ");

	pos=find_if(coll.begin(),coll.end(),bind2nd(greater<int>(),5));//查找第一个大于5的元素,返回的是位置,位置以0开始

	cout<<"the "<<distance(coll.begin(),pos)+1<<". elements is the first greater than 5"<<endl;

	pos=find_if(coll.begin(),coll.end(),not1(bind2nd(modulus<int>(),3)));//查找第一个可以被3整除的元素,返回的是位置,位置从0开始

	cout<<"the "<<distance(coll.begin(),pos)+1<<". elements is the first divsible by 3"<<endl;

	system("pause");
	return 0;
}


如果要搜寻前n个连续匹配值,你可能要用到:

search_n(beg,end,count,value)

search_n(beg,end,count,value,op)

第一个形式返回区间[beg,end)中第一组“连续count个元素值全等于value”的元素位置;

第二个形式返回区间[beg,end)中第一组“连续count个元素造成以下一元判断式结果为true”的元素位置;

如果没有找到匹配元素,两个都会返回end。


代码示例:

//search_n
#include"fuzhu.h"

using namespace std;

int main()
{
	vector<int> coll;

	INSERT_ELEMENTS(coll,1,3);

	coll.push_back(3);
	coll.push_back(3);
	coll.push_back(3);

	INSERT_ELEMENTS(coll,4,9);

	PRINT_ELEMENTS(coll,"coll: ");

	vector<int>::iterator pos;

	pos=search_n(coll.begin(),coll.end(),4,3);//查找是否存在连续的4个值3的元素  (beg,end,count,value)

	if(pos!=coll.end())
	{
		cout<<"Found "<<"start with "<<distance(coll.begin(),pos)+1<<". element"<<endl;
	}
	else
	{
		cout<<"Not Found"<<endl;
	}

	pos=search_n(coll.begin(),coll.end(),4,3,greater<int>());//查找是否存在连续的4个值大于3的元素 (beg,end,count,value,op)

	if(pos!=coll.end())
	{
		cout<<"Found "<<"start with "<<distance(coll.begin(),pos)+1<<". element"<<endl;
	}
	else
	{
		cout<<"Not Found"<<endl;
	}

	system("pause");
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值