#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
#include <string>
class GreaterFive
{
public:
bool operator()(int val)
{
return val > 5;
}
};
//内置数据类型
void test1()
{
vector<int> v1;
for (int i = 1; i < 10; i++)
{
v1.push_back(i);
}
vector<int>::iterator it = find_if(v1.begin(), v1.end(), GreaterFive());
if (it == v1.end())
{
cout << "没有找到" << endl;
}
else
{
cout << *it << endl;
}
}
//自定义数据类型
class Person
{
public:
string m_Name;
int m_Age;
Person(string name, int age)
{
m_Name = name;
m_Age = age;
}
};
class Greater20
{
public:
bool operator()(Person &p)
{
return p.m_Age > 20;
}
};
void test2()
{
vector<Person> v2;
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 30);
Person p4("ddd", 40);
Person p5("eee", 50);
v2.push_back(p1);
v2.push_back(p2);
v2.push_back(p3);
v2.push_back(p4);
v2.push_back(p5);
vector<Person>::iterator it1 = find_if(v2.begin(), v2.end(), Greater20());
if (it1 == v2.end())
{
cout << "没有找到" << endl;
}
else
{
cout << "姓名:" << (*it1).m_Name << "年龄:" << it1->m_Age << endl;
}
}
int main()
{
test1();
test2();
return 0;
}
常用查找算法 find_if
最新推荐文章于 2023-03-20 19:38:56 发布