-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path08_查找_count_if.cpp
93 lines (78 loc) · 1.41 KB
/
08_查找_count_if.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// count_if
/*
按条件统计元素个数
count_if(iterator beg, iterator end, _Pred);
按条件统计元素出现次数
beg 开始迭代器
end 结束迭代器
_Pred 谓词
*/
// 1、内置数据类型
class Greater20
{
public:
bool operator()(int val)
{
return val > 20;
}
};
void test01()
{
vector<int> v;
v.push_back(10);
v.push_back(40);
v.push_back(30);
v.push_back(20);
v.push_back(40);
v.push_back(20);
v.push_back(10);
int num = count_if(v.begin(), v.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 AgeGreater22
{
public:
bool operator()(const Person &p) const
{
return p.m_Age > 22;
}
};
void test02()
{
vector<Person> v;
Person p1("a", 20);
Person p2("b", 21);
Person p3("c", 22);
Person p4("d", 23);
Person p5("d", 24);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
// 统计大于22的人数
int num = count_if(v.begin(), v.end(), AgeGreater22());
cout << num << endl;
}
int main()
{
// test01();
test02();
return 0;
}