Created
July 9, 2019 09:51
-
-
Save wsgac/e5ce472cc03f4e513b25e6f63303948e to your computer and use it in GitHub Desktop.
Dynamic function creation example in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <functional> | |
| using namespace std; | |
| // Return a custom, parametrized adder function (lambda) | |
| auto make_adder(int n) { | |
| return [n](int x) { | |
| return x + n; | |
| }; | |
| } | |
| // Apply user-supplied function to each item in an array | |
| // and return a fresh array with the results | |
| int *map(int *arr, int n, function<int(int)> f) | |
| { | |
| int *new_arr = new int[n]; | |
| for (int i = 0; i < n; i++) | |
| { | |
| new_arr[i] = f(arr[i]); | |
| } | |
| return new_arr; | |
| } | |
| int main() | |
| { | |
| int addend, n = 10; | |
| int numbers[10] = {1,2,3,4,5,6,7,8,9,10}; | |
| cout << "Enter addend: " << endl; | |
| cin >> addend; | |
| int* mapped = map(numbers, 10, make_adder(addend)); | |
| for (int i = 0; i < 10; i++) { | |
| cout << mapped[i] << endl; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment