Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Call a function from a user input

Tags:

c++

python

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

like image 411
Lorenzo Beronilla Avatar asked Dec 17 '25 19:12

Lorenzo Beronilla


1 Answers

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.

like image 161
Costantino Grana Avatar answered Dec 20 '25 10:12

Costantino Grana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!