Skip to content

Instantly share code, notes, and snippets.

@wsgac
Created July 8, 2019 15:15
Show Gist options
  • Select an option

  • Save wsgac/2992d1dfa4510b0a71ecc6673d58485d to your computer and use it in GitHub Desktop.

Select an option

Save wsgac/2992d1dfa4510b0a71ecc6673d58485d to your computer and use it in GitHub Desktop.
Demonstration of function pointer array in C++
#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