admin管理员组文章数量:1794759
find
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
版权声明:本文标题:find 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686499936a74406.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论