-
Notifications
You must be signed in to change notification settings - Fork 29
/
stl_09_count_if.cpp
51 lines (39 loc) · 1020 Bytes
/
stl_09_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
// code_report
// https://youtu.be/-iw-wMzqG-Q
#include <vector>
#include <numeric>
#include <algorithm>
#include <iostream>
void example1 ()
{
using namespace std;
vector<int> v = { 1, 2, 3, 1, 2 };
cout << count (v.begin (), v.end (), 1) << endl; // 2
cout << count (v.begin (), v.end (), 3) << endl; // 1
}
void example2 ()
{
using namespace std;
vector<int> v = { 1, 2, 3, 1, 2 };
auto is_odd = [](auto e) { return e % 2 == 1; };
cout << count_if (v.begin (), v.end (), is_odd) << endl; // 3
}
namespace my {
template<class InIt, class T>
auto count (InIt first, InIt last, const T& val) {
return std::reduce (first, last, 0, [val](auto i, auto e) { return i + (e == val); });
}
}
void example3 ()
{
std::vector<int> v = { 1, 2, 3, 1, 2 };
std::cout << my::count (v.begin (), v.end (), 1) << std::endl; // 2
std::cout << my::count (v.begin (), v.end (), 3) << std::endl; // 1
}
int main ()
{
example1 ();
example2 ();
example3 ();
return 0;
}