Lorenzo Beronilla
Lorenzo Beronilla

Reputation: 55

C++: Call a function from a user input

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

Upvotes: 3

Views: 1830

Answers (1)

Costantino Grana
Costantino Grana

Reputation: 3428

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.

Upvotes: 7

Related Questions