#include using namespace std; /* In C, I'd have written something like this: * void apply_to_all(int *list, int (*function)(int), size_t length){ * But in C++, when you capture the parameter sum, for task 2, that changes the type * of the function to something that can't really be described in C syntax, thus the use * of the template. You don't have to explicitly instantiate the template, though, just * use it like a normal function, and it'll work. See the example. */ template void apply_to_all(int *list, ftype function, size_t length){ for(int i = 0; i < length; i++) list[i] = function(list[i]); } string to_string(int *array, size_t length){ string retval = "["; for(int i = 0; i < length; i++) retval += (i+1) < length? to_string(array[i]) + ", ":to_string(array[i]); retval += "]"; return retval; } int square(int x){ return x*x; } int main(){ int demo_array[] = {5, 10, 15, 20}; cout << "Initial Array: " << to_string(demo_array, 4) << endl; /* Here's an example of how apply_to_all works with a non-lambda function */ apply_to_all(demo_array, square, 4); cout << "With all numbers squared: " << to_string(demo_array, 4) << endl; /* Now let's divide each number by 10, with a lambda function */ apply_to_all(demo_array, [](int x){return x/10;}, 4); cout << "With each number divided by 10: " << to_string(demo_array, 4) << endl; /* If it makes you feel better about it, you can space it out with more lines. * We'll multiply each number by 5 this time */ apply_to_all(demo_array, [](int x){ return x * 5; } , 4); /* But now, the end looks a little goofy (this is the end of the call to apply_to_all); */ cout << "Multiplied by 5: " << to_string(demo_array, 4) << endl; /* Enough examples, your turn! */ int array[] = {3, 6, 9, 12, 15, 18, 21, 24, 27, 30}; // Length is 10 cout << "Initial test Array: " << to_string(array, 10) << endl; /* Task 1: Divide each number by 3 */ cout << "Divided by 3: " << to_string(array, 10) << endl; /* Task 2: Add up all the numbers in the array * Note: You'll have to capture sum for this one */ int sum = 0; cout << "The sum is: " << sum << endl; /* Task 3: For each number, if it's odd, multiply it by 100 */ cout << "With each odd number multipled by 100: " << to_string(array, 10) << endl; /* Task 4: Replace the middle 4 numbers with a 4 * Note: You'll have to start partway through (array + ...) and specify less than the full length */ cout << "With 4's in the middle: " << to_string(array, 10) << endl; return 0; }