1.功能:按条件查找元素
2.函数原型
- find_if( iterator beg, iterator end, _pred)
- 按值查找元素,找到的话返回指定位置的迭代器,找不到则返回结束迭代器位置
- beg :开始迭代器
- end :结束迭代器
- _pred :函数或者谓词 (返回bool类型的仿函数)
#include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; class GreaterFive { public: bool operator()(int val) { return val > 5; } }; void test1() { vector<int> v; for (int i = 0; i < 10; i++) { v.push_back(i); } vector<int>::iterator pos = find_if(v.begin(), v.end(), GreaterFive()); if (pos == v.end()) { cout << "未找到!" << endl; } else { //输出第一个大于5的数 cout << "找到>5的数字:" << *pos << endl; //输出全部大于5的数 while (pos!=v.end()) { cout << *pos++ << " " << endl; } } } //查找自定义数据类型 class person { public: person(string name, int age) { this->myname = name; this->myage = age; } string myname; int myage; }; class Greater20 { public: bool operator()(person& p) { return p.myage > 20; } }; void test2() { vector<person> v; person p1("aaa", 10); person p2("aaa", 20); person p3("aaa", 30); person p4("aaa", 40); v.push_back(p1); v.push_back(p2); v.push_back(p3); v.push_back(p4); //找年龄>20 vector<person>::iterator pos = find_if(v.begin(), v.end(), Greater20()); if (pos == v.end()) cout << "没有找到!" << endl; else cout << "找到姓名: " << pos->myname << " 年龄:" << pos->myage << endl; } int main() { test1(); test2(); return 0; }
更多推荐
find_if函数
发布评论