#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
//count_if(iterator begin, iterator end, _Pred);按条件统计元素出现次数
//_Pred为谓词(即返回类型为bool的仿函数)
//统计内置数据类型
class Count20
{
public:
bool operator()(const int val)
{
return val > 20;
}
};
void test0801()
{
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(20);
v.push_back(10);
v.push_back(40);
v.push_back(160);
int cnt=count_if(v.begin(), v.end(), Count20());//使用仿函数匿名对象指定查找规则
cout << "找到了" << cnt << "个" << endl;
}
//统计自定义数据类型
class Person
{
public:
Person(string name,int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
class CountPerson
{
public:
bool operator()(const Person p)
{
if (p.m_Name == "xian")
return true;
return false;
}
};
void test0802()
{
vector<Person> v;
Person p1("xian", 11);
Person p2("si", 21);
Person p3("xian", 11);
Person p4("fan", 31);
Person p5("xan", 41);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
int cnt = count_if(v.begin(), v.end(), CountPerson());//使用仿函数匿名对象指定查找规则
cout << "找到了" << cnt << "个" <<"xian"<< endl;
}
int main()
{
test0801();
test0802();
system("pause");
return 0;
}
网友评论