功能描述:
- 查找指定元素,找到返回指定元素的迭代器,找不到返回结束迭代器end()
#include<iostream> #include<vector> #include<functional> #include<algorithm> #include<string> using namespace std; //常用查找算法 find //查找 内置数据类型 void test1() { vector<int> v; for (int i = 0; i < 10; i++) { v.push_back(i); } //查找容器中是否有 元素 5 vector<int>::iterator it = find(v.begin(), v.end(), 5); if (it == v.end()) { cout << "没有找到元素5" << endl; } else cout << "找到"<<*it << endl; } //查找自定义类型 class Person { public: Person(int a,string s) { age = a; name = s; } bool operator==(const Person& p) { if (this->name == p.name && this->age == p.age) { return true; } else return false; } int age; string name; }; void test2() { vector<Person> v; Person p1(10, "dan"); Person p2(12, "shao"); Person p3(14, "fan"); Person p4(8, "yang"); v.push_back(p1); v.push_back(p2); v.push_back(p3); v.push_back(p4); Person p5(8, "yang"); //查找容器中是否有 元素 5 vector<Person>::iterator it = find(v.begin(), v.end(), p5); if (it == v.end()) { cout << "没有找到元素5" << endl; } else cout << "姓名: " << it->name <<" 年龄:"<<it->age<< endl; } int main() { test1(); test2(); return 0; }
标签:end,back,C++,Person,查找,include,find From: https://www.cnblogs.com/ggbond00/p/17201955.html