功能描述:
- 按条件统计元素个数
函数原型:
- count_if(iterator beg, iterator end, _Pred);
//按条件统计元素出现次数
//beg开始迭代器
//end结束迭代器
//_Pred谓词
代码演示:
#include<iostream>using namespace std;#include<algorithm>#include<vector>#include<string>//常用查找算法 count_if//1、统计内置数据类型class Greater20 {public:bool operator()(int val) {return val > 20;}};void test01() {vector<int>a;a.push_back(10);a.push_back(20);a.push_back(40);a.push_back(20);a.push_back(30);a.push_back(40);//统计大于20的元素个数int num = count_if(a.begin(), a.end(), Greater20());cout << "大于20的元素个数为:" << num << endl;}//2、统计自定义数据类型class Person {public:Person(string name, int age) {this->m_Name = name;this->m_Age = age;}string m_Name;int m_Age;};class Greater18 {public:bool operator()(const Person& p) {return p.m_Age > 18;}};void test02() {vector<Person>v;Person p1("WTY1", 18);Person p2("WTY2", 19);Person p3("WTY3", 20);Person p4("WTY4", 19);v.push_back(p1);v.push_back(p2);v.push_back(p3);v.push_back(p4);//统计大于18岁的人员个数int num = count_if(v.begin(), v.end(), Greater18());cout << "大于18岁的人员个数为:" << num << endl;}int main() {test01();test02();return 0;}
运行结果:
