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();
}