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:
- you need to check that user input is fine
- you need to pass parameters to your Python functions.
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.
std::mapwith the function name as the key and a function pointer as the value.std::maporstd::unordered_mapto store function pointers. But even better would be to storestd::functionin the map. By the way, what if the user input is not in{'x', 'z'}?functions[input()]()doesn't provide any.