#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
class Greater1{
public:
bool operator()(int val){
return val>1;
}
};
//内置数据类型
void test(){
vector<int>v;
v.push_back(1);
v.push_back(2);
v.push_back(1);
v.push_back(1);
int num=count_if(v.begin(),v.end(),Greater1());
cout<<"大于1的个数为:"<<num<<endl;
}
//自定义数据类型
class Person{
public:
string m_Name;
int m_Age;
Person(string name,int age){
m_Name=name;
m_Age=age;
}
};
class Greater10{
public:
bool operator()(const Person & p){
return p.m_Age>10;
}
};
void test2(){
Person p1("aaa", 10);
Person p2("bbb", 20);
Person p3("ccc", 10);
Person p4("ddd", 10);
Person p5("eee", 10);
vector<Person>v1;
v1.push_back(p1);
v1.push_back(p2);
v1.push_back(p3);
v1.push_back(p4);
v1.push_back(p5);
int num=count_if(v1.begin(),v1.end(),Greater10());
cout<<"年龄大于10的个数:"<<num<<endl;
}
int main(){
test();
test2();
return 0;
}
常用查找算法-count_if
最新推荐文章于 2024-08-08 15:12:59 发布