python - C++:从用户输入调用函数
问题描述
在 python 中,当我有几个基于用户输入调用的不同函数时,我有一个字典,其中用户输入作为键,函数名作为值。
def x(y):
return y
def z(y):
return y
functions = {
'x': x
'z': z
}
print(functions[input()]())
有没有人知道如何在 C++ 中做到这一点?
解决方案
您可以在 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++ 中这样做,因为:
- 您需要检查用户输入是否正常
- 您需要将参数传递给您的 Python 函数。
Python 版本和 C++ 版本的主要区别在于 Python 函数可以有不同的参数和返回值,即使它们共享相同的结构,输入和输出类型也可以不同。您问题中的函数x
接受任何内容。人们可能会争论这样做的用处。
在任何情况下,您也可以在 C++ 中做到这一点,但这要困难得多。
推荐阅读
- autohotkey - 使用 ControlClick 和 WinTitle 的问题
- wordpress - wordpress 在将文本显示给浏览器之前替换文本
- cypress - 赛普拉斯:如果未找到来自“cy.route()”的请求,则测试失败
- javascript - 角反应形式日期设定值
- flutter - 在 Flutter 中,如何使用 WebView 制作简单的浏览器小部件?
- r - 将大型数据集从长转换为宽(450 多个值变量)
- rdf - Semantic Web - Turtle 和 JSON-LD 是一回事吗 - 一种保存 RDF 的方法
- python - Python math.log 函数数学域错误
- android - 使用数据绑定在片段活动中映射片段?
- c# - Opencvsharp4.windows 'OpenCvSharp.Mat' 的类型初始化程序抛出异常。创建安装文件后收到此错误