I have stored the name of some functions in an array, but now I need to use those functions. When the user chooses a function to access, how can I use the function name I saved to reach the intended function? Or can I?
#include <iostream>
#include <string>
struct Func {
std::string name;
void (* fptr )(); // pointer to a function that takes no parameters and returns nothing.
};
void one() { std::cout << "\nfunc one\n\n"; }
void two() { std::cout << "\nfunc two\n\n"; }
void three() { std::cout << "\nfunc three\n\n"; }
int main() {
Func funcs[] = {
{ "one", one },
{ "two", two },
{ "three", three },
{ "", nullptr } // a null function pointer marks the end of the table
};
while (true) {
int n = 0;
for ( ; funcs[n].fptr != nullptr; n++)
std::cout << n + 1 << ". " << funcs[n].name << '\n';
std::cout << n + 1 << ". quit\n";
int choice = -1;
while (true) {
std::cout << "What function do you want: ";
std::cin >> choice;
if (choice >= 1 && choice <= n + 1)
break;
std::cout << "Enter a number from 1 to " << n + 1 << ".\n";
}
if (choice == n + 1)
break;
funcs[choice - 1].fptr();
}
}
#include <iostream>
#include <map>
#include <functional>
usingnamespace std;
int Add(int a, int b)
{
return a + b;
}
int Sub(int a, int b)
{
return a - b;
}
int Mul(int a, int b)
{
return a * b;
}
int Div(int a, int b)
{
return a / b;
}
int main()
{
map<string, function<int(int,int)>> funcs
{
{ "Add", Add },
{ "Sub", Sub },
{ "Mul", Mul },
{ "Div", Div },
};
for (auto& kv : funcs)
cout << kv.first << " : " << kv.second(4,5) << endl;
return 0;
}