功能描述:

    • 按条件查找元素

    函数原型:

    • find_if(iterator beg, iterator end, _Pred);

    //按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
    //beg开始迭代器
    //end结束迭代器
    //_Pred函数或者谓词(返回bool类型的仿函数)

    代码演示:

    1. #include<iostream>
    2. using namespace std;
    3. #include<algorithm>
    4. #include<vector>
    5. #include<string>
    6. //常用查找算法 find_if
    7. //1、查找内置数据类型
    8. class BigFive {
    9. public:
    10. bool operator()(int val) {
    11. return val > 5;
    12. }
    13. };
    14. void test01() {
    15. vector<int>a;
    16. for (int i = 0; i < 10; i++) {
    17. a.push_back(i);
    18. }
    19. //查找容器中是否有5这个元素
    20. vector<int>::iterator it = find_if(a.begin(), a.end(), BigFive());
    21. if (it == a.end()) {
    22. cout << "没有找到该元素!" << endl;
    23. }
    24. else {
    25. cout << "找到大于5的数字为:" << *it << endl;
    26. }
    27. }
    28. //2、查找自定义数据类型
    29. class Person {
    30. public:
    31. string m_Name;
    32. int m_Age;
    33. Person(string name, int age) {
    34. this->m_Name = name;
    35. this->m_Age = age;
    36. }
    37. };
    38. class Grater20 {
    39. public:
    40. bool operator()(Person& p) {
    41. return p.m_Age > 18;
    42. }
    43. };
    44. void test02() {
    45. vector<Person>a;
    46. //创建数据
    47. Person p1("WTY1", 18);
    48. Person p2("WTY2", 19);
    49. Person p3("WTY3", 20);
    50. Person p4("WTY4", 21);
    51. //放入容器中
    52. a.push_back(p1);
    53. a.push_back(p2);
    54. a.push_back(p3);
    55. a.push_back(p4);
    56. //查找年龄大于18岁的人
    57. vector<Person>::iterator it = find_if(a.begin(), a.end(), Grater20());
    58. if (it == a.end()) {
    59. cout << "没有找到这个人!" << endl;
    60. }
    61. else {
    62. cout << "找到这个人,姓名:" << it->m_Name << " 年龄:" << it->m_Age << endl;
    63. }
    64. }
    65. int main() {
    66. test01();
    67. test02();
    68. return 0;
    69. }

    运行结果:
    image.png