In python, when i have several different functions that get called based on user input, I have a dictionary with the user input as a key and the function name as the value.
def x(y):
return y
def z(y):
return y
functions = {
'x': x
'z': z
}
print(functions[input()]())
Does anybody have any idea of how this can be done in c++?
You can do something similar in C++ like this:
#include <functional>
#include <iostream>
#include <string>
#include <unordered_map>
void one()
{
std::cout << "Hello, I'm one.\n";
}
void two()
{
std::cout << "Hello, I'm two.\n";
}
int main()
{
std::unordered_map<std::string, std::function<void()>> functions = {
{"one", one},
{"two", two}
};
std::string s;
std::cin >> s;
functions[s]();
return 0;
}
Then, you shouldn't do it neither in Python, nor in C++ since:
The main difference between the Python version and the C++ one is that Python functions could have different parameters and return values, and that even if they share the same structure, input and output types can be different. Function x in your question accepts anything. One could argue on the usefulness of that.
In any case you can do also that in C++, but it is way harder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With