18.2.5【STL常用查找算法count_if】

  1 #include<iostream>
  2 #include<cstdlib>
  3 using namespace std;
  4 #include<vector>
  5 #include<algorithm>
  6 #include<string>
  7 
  8 
  9 /*
 10      5.2.6 count_if
 11         按条件统计元素个数
 12         count_if(iterator beg, iterator end, _Pred);
 13         // 按条件统计元素出现次数
 14         // beg 开始迭代器
 15         // end 结束迭代器
 16         // _Pred 谓词
 17 */
 18 
 19 
 20 class Greater3
 21 {
 22 public:
 23     bool operator()(int val)
 24     {
 25         return val > 3;
 26     }
 27 };
 28 
 29 
 30 void test526() //内置数据类型
 31 {
 32     vector<int> v;
 33     v.push_back(1);
 34     v.push_back(2);
 35     v.push_back(4);
 36     v.push_back(5);
 37     v.push_back(2);
 38     v.push_back(4);
 39     v.push_back(4);
 40     v.push_back(3);
 41 
 42     int num = count_if(v.begin(), v.end(), Greater3());
 43     cout << "v中大于3的元素个数:" << num << endl;
 44 }
 45 
 46 
 47 class Person
 48 {
 49 public:
 50     string name;
 51     int age;
 52 
 53 public:
 54     Person(string _name, int _age)
 55     {
 56         this->name = _name;
 57         this->age = _age;
 58     }
 59 };
 60 
 61 
 62 class Greater20
 63 {
 64 public:
 65     bool operator()(const Person & p)
 66     {
 67         return p.age > 20;
 68     }
 69 };
 70 
 71 
 72 void test526_1() //自定义数据类型
 73 {
 74     vector<Person> vv;
 75     Person p1("aaa", 10);
 76     Person p2("bbb", 20);
 77     Person p3("ccc", 30);
 78     Person p4("ddd", 30);
 79     Person p5("eee", 40);
 80     Person p6("fff", 30);
 81     vv.push_back(p1);
 82     vv.push_back(p2);
 83     vv.push_back(p3);
 84     vv.push_back(p4);
 85     vv.push_back(p5);
 86     vv.push_back(p6);
 87 
 88     //统计vv中年龄大于20的有多少人
 89     int num = count_if(vv.begin(), vv.end(), Greater20());
 90     cout << "num:" << num << endl;
 91 }
 92 
 93 
 94 int main()
 95 {
 96     test526();
 97     test526_1();
 98 
 99     system("pause");
100     return 0;
101 }

 

posted @ 2021-05-13 11:51  yub4by  阅读(69)  评论(0)    收藏  举报