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 @   yub4by  阅读(65)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示