查找算法find_if

黑马246
#include
#include
#include
#include
using namespace std;
class greaterFive
{
public:
bool operator()(int val)
{
return val > 5;
}
};
class person
{
public:
person(string name, int age)
{
m_name = name;
m_age = age;
}
//重载底层find知道如何对比person数据类型
bool operator
(const person& p)
{
if (this->m_name == p.m_name && this->m_age == p.m_age)
{
return true;
}
else
{
return false;
}
}
string m_name;
int m_age;
};
class greater20
{
public:
bool operator()(person &p)
{
return p.m_age > 20;
}
};
//find_if

//查找内置数据类型
void test01()
{
vectorv;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector::iterator it = find_if(v.begin(), v.end(), greaterFive());
if (it == v.end())
{

	cout << "can not find" << endl;
}
else
{
	cout << "find it" <<*it<< endl;
}

}
//查找自定义数据类型
void test02()
{
vectorv;
person p1(“aa”, 10);
person p2(“bb”, 20);
person p3(“cc”, 30);
person p4(“dd”, 40);
person p5(“ee”, 50);

v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
vector<person>::iterator it = find_if(v.begin(), v.end(),greater20());
if (it != v.end())
{
	cout << "find it" <<it->m_name<<"  " << it->m_age << endl;
}
else
{
	cout << "can not find" << endl;
}

}
int main()
{
test02();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值