#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
//常用查找算法
//find_if
class GreaterFive
{
public:
bool operator()(int val)
{
return val > 5;
}
};
//查找 内置数据类型
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//查找 容器中 是否有 大于5的元素
vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());
if (it == v.end())
{
cout << "未找到!" << endl;
}
else
{
cout << "找到了!" << *it << endl;
}
}
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
public:
string m_Name;
int m_Age;
};
class Greate20
{
public:
bool operator()(Person &p)
{
return p.m_Age > 20;
}
};
// 查找 自定义数据类型
void test02()
{
vector<Person>v;
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 30);
Person p4("ddd", 40);
Person pp("eee", 50);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(pp);
//找年龄大于20岁的
vector<Person>::iterator it = find_if(v.begin(), v.end(), Greate20());
if (it == v.end())
{
cout << "未找到!" << endl;
}
else
{
cout << "找到了!" << "姓名:" << it->m_Name << " 年龄: " << it->m_Age << endl;
}
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}
02-08
422
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交