forked from teseoch/CPP-Fall-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path106-function_sampler.cpp
66 lines (55 loc) · 1.39 KB
/
106-function_sampler.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
#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"
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.
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.
for (auto x : V)
{
p(x);
}
std::cout << std::endl;
// Task 3: See above.
/*
auto op = get_operation("multiply");
std::cout << "Product: " << op(V);
std::cout << std::endl;
*/
return 0;
}