功能描述:

    • 按条件统计元素个数

    函数原型:

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

    //按条件统计元素出现次数
    //beg开始迭代器
    //end结束迭代器
    //_Pred谓词

    代码演示:

    1. #include<iostream>
    2. using namespace std;
    3. #include<algorithm>
    4. #include<vector>
    5. #include<string>
    6. //常用查找算法 count_if
    7. //1、统计内置数据类型
    8. class Greater20 {
    9. public:
    10. bool operator()(int val) {
    11. return val > 20;
    12. }
    13. };
    14. void test01() {
    15. vector<int>a;
    16. a.push_back(10);
    17. a.push_back(20);
    18. a.push_back(40);
    19. a.push_back(20);
    20. a.push_back(30);
    21. a.push_back(40);
    22. //统计大于20的元素个数
    23. int num = count_if(a.begin(), a.end(), Greater20());
    24. cout << "大于20的元素个数为:" << num << endl;
    25. }
    26. //2、统计自定义数据类型
    27. class Person {
    28. public:
    29. Person(string name, int age) {
    30. this->m_Name = name;
    31. this->m_Age = age;
    32. }
    33. string m_Name;
    34. int m_Age;
    35. };
    36. class Greater18 {
    37. public:
    38. bool operator()(const Person& p) {
    39. return p.m_Age > 18;
    40. }
    41. };
    42. void test02() {
    43. vector<Person>v;
    44. Person p1("WTY1", 18);
    45. Person p2("WTY2", 19);
    46. Person p3("WTY3", 20);
    47. Person p4("WTY4", 19);
    48. v.push_back(p1);
    49. v.push_back(p2);
    50. v.push_back(p3);
    51. v.push_back(p4);
    52. //统计大于18岁的人员个数
    53. int num = count_if(v.begin(), v.end(), Greater18());
    54. cout << "大于18岁的人员个数为:" << num << endl;
    55. }
    56. int main() {
    57. test01();
    58. test02();
    59. return 0;
    60. }

    运行结果:
    image.png