功能描述:
- 查找指定元素,找到返回指定元素的迭代器,找不到返回结束迭代器end()
函数原型:
- find(iterator beg, iterator end, value);
//按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
//beg开始迭代器
//end结束迭代器
//value查找的元素
代码演示:
#include<iostream>using namespace std;#include<algorithm>#include<vector>#include<string>//常用查找算法 find//查找内置数据类型void test01() {vector<int>a;for (int i = 0; i < 10; i++) {a.push_back(i);}//查找容器中是否有5这个元素vector<int>::iterator it = find(a.begin(), a.end(), 5);if (it == a.end()) {cout << "没有找到该元素!" << endl;}else {cout << "找到:" << *it << endl;}}class Person {public:string m_Name;int m_Age;Person(string name, int age) {this->m_Name = name;this->m_Age = age;}//重载== 让底层find知道如何对比person数据类型bool operator==(const Person& p1) {if (this->m_Name == p1.m_Name && this->m_Age == p1.m_Age) {return true;}else {return false;}}};//查找自定义的数据类型void test02(){vector<Person>a;//创建数据Person p1("WTY1", 18);Person p2("WTY2", 19);Person p3("WTY3", 20);Person p4("WTY4", 21);//放入容器中a.push_back(p1);a.push_back(p2);a.push_back(p3);a.push_back(p4);//查找自定义数据类型时,必须要重载==vector<Person>::iterator it = find(a.begin(), a.end(), p2);if (it == a.end()) {cout << "没有找到该元素!" << endl;}else {cout << "找到元素,姓名:" << it->m_Name << " 年龄:" << it->m_Age << endl;}}int main() {test01();test02();return 0;}
运行结果:
