1.功能:查找指定元素,找到返回指定元素的迭代器,找不到返回结束迭代器end();
2.函数原型:
- find(iterator beg, iterator end , value)
- beg 开始迭代器
- end 结束迭代器
- value 查找的元素
#include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; void test1() { vector<int> v; for (int i = 0; i < 10; i++) { v.push_back(i); } vector<int>::iterator pos = find(v.begin(), v.end(), 5); if (pos == v.end()) { cout << "未找到!" << endl; } else { cout << "找到:" << *pos << endl; } } class person { public: person(string name, int age) { this->myname = name; this->myage = age; } //重载 == 让底层find知道如何对比person数据类型 bool operator==(const person &p) { if (this->myname == p.myname && this->myage == p.myage) return true; else return false; } string myname; int myage; }; //查找自定义数据类型 void test2() { 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 pos = find(v.begin(), v.end(), p2); if (pos == v.end()) { cout << "未找到!" << endl; } else { cout << "找到,姓名:" << (*pos).myname <<" 年龄:"<<pos->myage<< endl; } } int main() { test1(); test2(); return 0; }