首页 > 解决方案 > C++:从用户输入调用函数

问题描述

在 python 中,当我有几个基于用户输入调用的不同函数时,我有一个字典,其中用户输入作为键,函数名作为值。

def x(y):
    return y

def z(y):
    return y

functions = {
    'x': x
    'z': z
}

print(functions[input()]())

有没有人知道如何在 C++ 中做到这一点?

标签: pythonc++

解决方案


您可以在 C++ 中执行类似的操作,如下所示:

#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;
}

然后,你不应该在 Python 和 C++ 中这样做,因为:

  1. 您需要检查用户输入是否正常
  2. 您需要将参数传递给您的 Python 函数。

Python 版本和 C++ 版本的主要区别在于 Python 函数可以有不同的参数和返回值,即使它们共享相同的结构,输入和输出类型也可以不同。您问题中的函数x接受任何内容。人们可能会争论这样做的用处。

在任何情况下,您也可以在 C++ 中做到这一点,但这要困难得多。


推荐阅读