forked from Ovievilla/CPP-Fall-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path106-function_sampler.cpp
More file actions
76 lines (65 loc) · 1.77 KB
/
106-function_sampler.cpp
File metadata and controls
76 lines (65 loc) · 1.77 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
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <vector>
#include <functional>
void print_int(int z)
{
std::cout << "print_int: " << z << std::endl;
}
int sum_vector(std::vector<int> &V)
{
int sum{0};
for (auto x : V)
sum += x;
return sum;
}
int mul_vector(std::vector<int> &V)
{
int product{1};
for (auto x : V)
product *= x;
return product;
}
//Task3 : Write a function get_operation which takes
// a string and returns one of the above functions:
// - The return value is the sum_vector function
// if the provided string is "sum"
// - The return value is the sum_vector function
// if the provided string is "multiply"
std::function<int(std::vector<int> &)> get_operation(const std::string &op)
{
if (op == "sum")
return sum_vector;
else if (op == "multiply")
return mul_vector;
else
throw std::runtime_error("bad");
}
int main()
{
std::vector<int> V{6, 10, 17};
for (auto x : V)
{
print_int(x);
}
// Task 1: Create a variable SF which refers to the
// sum_vector function, such that the call below
// works correctly.
//int sum_vector(std::vector<int> &V)
std::function</*type of the function*/ int(std::vector<int> &)> SF = sum_vector;
auto sum = SF(V);
std::cout << "Sum = " << sum << std::endl;
// Task 2: Create a variable p which refers to the print_int
// function, such that the following loop prints the
// elements of V.
std::function<void(int)> p = print_int;
for (auto x : V)
{
p(x);
}
std::cout << std::endl;
// Task 3: See above.
auto op = get_operation("sum");
std::cout << "Product: " << op(V);
std::cout << std::endl;
return 0;
}