1.功能:按条件统计元素个数
2.函数原型
- count_if( iterator beg, iterator end , _pred)
- beg 开始迭代器
- end 结束迭代器
- _pred 谓词
#include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; //统计内置数据类型 class Greater6 { public: bool operator()(int val) { return val > 6; } }; void test1() { vector<int> v; v.push_back(6); v.push_back(8); v.push_back(6); v.push_back(7); v.push_back(3); v.push_back(6); int num = count_if(v.begin(), v.end(), Greater6()); cout << "大于6的个数为:" << num << endl; // 2个 } //统计自定义数据类型 class person { public: person(string name, int age) { this->myname = name; this->myage = age; } string myname; int myage; }; class AgeGreater20 { public: bool operator()(const person& p) { return p.myage > 20; } }; void test2() { vector<person> v; person p1("刘备", 20); person p2("关羽", 20); person p3("张飞", 20); person p4("赵云", 30); person p5("曹操", 40); v.push_back(p1); v.push_back(p2); v.push_back(p3); v.push_back(p4); v.push_back(p5); //统计大于20岁人员个数 int num = count_if(v.begin(), v.end(), AgeGreater20()); cout << "年龄大于20的人员个数为:" << num << endl; // 2个 } int main() { test1(); test2(); return 0; }