C++ //count_if //按条件统计元素个数 //自定义和 内置

  1 //按条件统计元素个数
  2 //count_if
  3 
  4 #include <iostream>
  5 #include<string>
  6 #include<vector>
  7 #include<algorithm>
  8 
  9 using namespace std;
 10 
 11 class Greater20
 12 {
 13 public:
 14     bool operator()(int val)
 15     {
 16         return val > 20;
 17     }
 18 };
 19 
 20 //内置查找
 21 void test01()
 22 {
 23     vector<int>v;
 24     v.push_back(10);
 25     v.push_back(40);
 26     v.push_back(80);
 27     v.push_back(30);
 28     v.push_back(30); 
 29     v.push_back(50);
 30     v.push_back(20);
 31     v.push_back(10);
 32 
 33 
 34     //大于20
 35     int num =count_if(v.begin(), v.end(), Greater20());
 36 
 37     cout << "大于20的元素个数为:" << num << endl;
 38 
 39 
 40 }
 41 
 42 //自定义数据类型
 43 class Person
 44 {
 45 public:
 46     Person(string name, int age)
 47     {
 48         this->m_Name = name;
 49         this->m_Age = age;
 50     }
 51 
 52 
 53 
 54     string m_Name;
 55     int m_Age;
 56 };
 57 
 58 class Greate30
 59 {
 60 public:
 61     bool operator()(const Person &p)
 62     {
 63         return p.m_Age > 30;
 64     }
 65 
 66 
 67 
 68     string m_Name;
 69     int m_Age;
 70 };
 71 void test02()
 72 {
 73 
 74     vector<Person>v;
 75     Person p1("刘备", 30);
 76     Person p2("张三", 50);
 77     Person p3("李四", 60);
 78     Person p4("王五", 10);
 79     Person p5("曹操", 50);
 80     Person p6("赵云", 70);
 81 
 82     v.push_back(p1);
 83     v.push_back(p2);
 84     v.push_back(p3);
 85     v.push_back(p4);
 86     v.push_back(p5);
 87     v.push_back(p6);
 88 
 89     int num =count_if(v.begin(), v.end(), Greate30());
 90     cout << "年龄大于三十的有:" << num << endl;
 91 }
 92 int main()
 93 {
 94 
 95     test01();
 96     test02();
 97 
 98     system("pause");
 99     return 0;
100 }

 

posted on 2021-08-18 14:48  Bytezero!  阅读(85)  评论(0编辑  收藏  举报