3

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++?

3
  • 1
    In pretty much the same way, create a std::map with the function name as the key and a function pointer as the value. Commented Apr 21, 2020 at 5:50
  • 1
    You still can use std::map or std::unordered_map to store function pointers. But even better would be to store std::function in the map. By the way, what if the user input is not in {'x', 'z'}? Commented Apr 21, 2020 at 5:50
  • One more issue: each function in your snippet accepts an argument. The functions[input()]() doesn't provide any. Commented Apr 21, 2020 at 5:55

1 Answer 1

7

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:

  1. you need to check that user input is fine
  2. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yah I usually put the input inside a try-except block and have some sort of while loop. Thanks for the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.