查找算法find 和find_if 的区别

1:find查找函数原型为find(_InIt _First, const _InIt _Last, const  _Ty& _Val)、

first 为迭代器起始位置

last为迭代器起始位置

val为查到数据 

!,查找内置数据类型直接赋值就可以了但是自定义数据类型要重载 == ,不然编译器不知道怎样判断

2:fand_if查找函数原型为find_if(_InIt _First, const _InIt _Last, _Pr _Pred)

first 为迭代器起始位置

last为迭代器起始位置

Pr _Pred是谓词,需要自己创建

代码如下

先是用find 和find_if查找int类型数据 3在容器是否存在

然后用find 和find_if查找Person自定义数据类型在容器中是否存在

#include<iostream>
using namespace std;
#include<vector>
#include<string>
#include<algorithm>
class Person
{
public:
	Person(string name, int  age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	bool operator==(const Person &p)
	{
		if (this->m_age == p.m_age && this->m_name == p.m_name)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	string m_name;
	int m_age;
};
class Great20     //创建谓词
{
public:
	bool operator()(Person& p)
	{
		return p.m_age == 20;
	}
};
class Great3   //创建谓词
{
public:
	bool operator()(int& val)
	{
		return val == 3;
	}
};
void test()
{   
	vector<int> v1;
	v1.push_back(1);
	v1.push_back(2);
	v1.push_back(3);
	v1.push_back(4);
	vector<int>::iterator dit = find_if(v1.begin(), v1.end(), Great3());
	if (dit != v1.end())
	{
		cout << "find the number   " << *dit << endl;
	}
	else
	{
		cout << "not find the number" << endl;
	}
	vector<int>::iterator uit = find(v1.begin(), v1.end(), 3);
	if (uit != v1.end())
	{
		cout << "find the number   " << *uit << endl;
	}
	else
	{
		cout << "not find the number" << endl;
	}
	vector<Person>v;
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);

	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4);
	vector<Person>::iterator it = find_if(v.begin(), v.end(), Great20());
	cout << "name is : " << it->m_name << "   are is: " << it->m_age << endl;
	Person pp("bbb", 20);
    vector<Person>::iterator cit = find(v.begin(), v.end(), pp);
     if (cit != v.end())
     {
     	cout << "find the Person" << " name is " << cit->m_name << "   age is  " << it->m_age << endl;
     }
     else
     {
     	cout << " no find the Person" << endl;
     }
}
int main()
{
	test();
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值