-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathlambda.cpp
More file actions
63 lines (50 loc) · 1.89 KB
/
lambda.cpp
File metadata and controls
63 lines (50 loc) · 1.89 KB
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
// lambda.cpp ---- 使用 lambda 表达式
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <ctime>
const long Size1 = 39L;
const long Size2 = 100 * Size1;
const long Size3 = 100 * Size2;
bool f3(int x) {return x % 3 == 0;}
bool f13(int x) {return x % 13 == 0;}
int main()
{
using std::cout;
std::vector<int> numbers(Size1);
std::srand(std::time(0));
std::generate(numbers.begin(), numbers.end(),std::rand);
// using function pointers
court << "Sample size = " << Size1 << '\n';
int count3 = std::count_if(numbers.begin(),numbers.end(),f3);
cout << "Count of nuumbers divisible by 3 : " << count3 << '\n';
int count13 = std::count_if(numbers.begin(),numbers.end(),f13);
cout << "Count of numbers divisible by 13 : " << count13 << "\n\n";
// increase number of numbers
numbers.resize(Size2);
std::generate(number.begin(),number.end(),std::rand);
cout << "Sample size = " << Size2 << '\n';
// using a functor
class f_mod
{
private:
int dv;
public:
f_mod(int d = 1) : dv(d) {}
bool operator() (int x) {return x % dv == 0;}
};
count3 = std::count_if(numbers.begin().numbers.end(),f_mod(3));
cout << "Count of numbers divisible by 3 : " << count3 << '\n';
count13 = std::count_if(numbers.begin(),numbers.end(),f_mod(13));
// increase number of numbers again
numbers.resize(Size3);
std::generate(numbers.begin(),numbers.end(),std::rand);
cout << "Sample size = " << Size3 << '\n';
// using lambdas
count3 = std::count_if(numbers.begin(),numbers.end(),[](int x) {return x % 3 == 0;});
cout << "Count of numbers divisible by 3 : " << count3 << '\n';
count13 = std::count_if(numbers.begin(),numbers.end(), [] (int x){return x % 13 == 0;});
cout << "Count of numbers divisible by 13 : " << count13 << '\n';
return 0;
}