Created
July 8, 2019 15:15
-
-
Save wsgac/2992d1dfa4510b0a71ecc6673d58485d to your computer and use it in GitHub Desktop.
Demonstration of function pointer array 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> | |
| using namespace std; | |
| int (*functions[4])(int) = { | |
| [](int x) -> int { | |
| return x + 10; | |
| }, | |
| [](int x) -> int { | |
| return x - 10; | |
| }, | |
| [](int x) -> int { | |
| return x * 10; | |
| }, | |
| [](int x) -> int { | |
| return x / 10; | |
| }}; | |
| int *map(int *arr, int n, int (*f)(int)) | |
| { | |
| 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 fun; | |
| int n = 10; | |
| int offset; | |
| cout << "Select function: " << endl; | |
| cin >> fun; | |
| cout << "Select offset: " << endl; | |
| cin >> offset; | |
| int arr[n]; | |
| cout << "Original array: " << endl; | |
| for (int i = 0; i < n; i++) | |
| { | |
| arr[i] = i + offset; | |
| cout << arr[i] << endl; | |
| } | |
| cout << "Mapped array: " << endl; | |
| int *new_arr = map(arr, n, functions[fun]); | |
| for (int i = 0; i < n; i++) | |
| { | |
| cout << new_arr[i] << endl; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment