C++ find和find_if

find_if(iterator beg, iterator end, _Pred);
按值查找元素,找到返回指定位置迭代器,找不到
则返回结束迭代器位置
_Pred:函数或谓词(返回bool类型的仿函数)

#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <algorithm>
#include <list>
#include <set>
#include <map>
#include <functional>
using namespace std;

//内置数据类型
void test1()
{
	vector<int> vt;
	vt.push_back(10);
	vt.push_back(20);
	vt.push_back(30);
	vt.push_back(40);
	
	//查询传入的值是否存在
	vector<int>::iterator it = find(vt.begin(), vt.end(), 30);
	if (it != vt.end())
	{
		cout<<"找到:"<<*it<<endl;
	}
	else
	{
		cout<<"没有找到"<<endl;
	}
}
//自定义数据类型
class Person
{
public:
	Person(string name, int age):m_name(name), m_age(age){}
	bool operator==(const Person p)
	{
		if (this->m_name == p.m_name && this->m_age == p.m_age)
		{
			return true;
		}
		
		return false;
	}
	string m_name;
	int m_age;
};


void test2()
{
	vector<Person> vt;
	Person p1("刘备", 38);
	Person p2("关羽", 35);
	Person p3("张飞", 30);
	Person p4("赵云", 28);
	vt.push_back(p1);
	vt.push_back(p2);
	vt.push_back(p3);
	vt.push_back(p4);
	
	Person p5("赵云", 28);
	//第三个参数传入的是一个对象类型,查询传入的对象是否存在
	vector<Person>::iterator it = find(vt.begin(), vt.end(), p5);
	if (it != vt.end())
	{
		cout<<"找到:"<<it->m_name<<","<<it->m_age<<endl;
	}
	else
	{
		cout<<"没有找到"<<endl;
	}
}

class MyCompare{
public:
	bool operator()(int var)
	{
		return var>5;
	}
};

//内置类型
void test3()
{
	vector<int> vt;
	for (int i=0; i<10; i++)
	{
		vt.push_back(i);
	}

	//条件查询,找到符合条件的第一个元素,不仅仅是比较,也可以==等运算符, 传入的是一个仿函数对象
	vector<int>::iterator it = find_if(vt.begin(), vt.end(), MyCompare());
	if (it != vt.end())
	{
		cout<<"找到:"<<*it<<endl;
	}
	else
	{
		cout<<"未找到"<<endl;
	}
}

//自定义数据类型
class MyCompare1
{
public:
	bool operator()(const Person p)
	{
		if (p.m_age >40)
		{
			return true;
		}
		
		return false;
	}
	string m_name;
	int m_age;
};

void test4()
{
	vector<Person> vt;
	Person p1("刘备", 38);
	Person p2("关羽", 35);
	Person p3("张飞", 30);
	Person p4("赵云", 28);
	vt.push_back(p1);
	vt.push_back(p2);
	vt.push_back(p3);
	vt.push_back(p4);
	
	//条件查询,仿函数定义查询条件
	vector<Person>::iterator it = find_if(vt.begin(), vt.end(), MyCompare1());
	if (it != vt.end())
	{
		cout<<"找到:"<<it->m_name<<","<<it->m_age<<endl;
	}
	else
	{
		cout<<"没有找到"<<endl;
	}
}


void test5()
{
	vector<int> vt;
	vt.push_back(10);
	vt.push_back(20);
	vt.push_back(30);
	vt.push_back(40);
	vt.push_back(40);

	//查找容器中相邻相同的元素,返回第一个元素的迭代器
	vector<int>::iterator it = adjacent_find(vt.begin(), vt.end());
	if (it != vt.end())
	{
		cout<<"找到:"<<*it<<endl;
		cout<<"找到:"<<*(it+1)<<endl;
	}
	else
	{
		cout<<"没有找到"<<endl;
	}
}
int main()
{
	test1();
	test2();
	test3();
	test4();
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值