find
示例:
#include<iostream>
using namespace std;
#include<vector>
class Person
{
public:
Person(string name,int age)
{
this->m_Name = name;
this->m_Age = age;
}
//重载operator== 底层find知道怎么对比自定义数据类型
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;
};
//利用find查找内置数据类型
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
vector<int>::iterator it = find(v.begin(), v.end(), 5);
if (it == v.end())
{
cout << "找不到" << endl;
}
else
{
cout << "找到:" << *it << endl;
}
}
//利用find查找自定义数据类型
void test02()
{
vector<Person>v;
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 30);
Person p4("ddd", 40);
Person p5("eee", 50);
Person pxx("eee", 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(v.begin(), v.end(), pxx);
if (it == v.end())
{
cout << "找不到" << endl;
}
else
{
cout << "找到 姓名为:" << it->m_Name << " 年龄为:" << it->m_Age << endl;
}
}
int main()
{
//test01();
test02();
return 0;
}
总结:利用find可以查找容器内的元素,返回的是迭代器