C++ map映射不同函数代码
时间: 2023-08-07 16:02:55 浏览: 259
可以使用C++中的std::map容器来实现这个功能。map是一个关联容器,它将键映射到值。可以使用map将不同的函数映射到不同的键上,然后通过键来调用相应的函数。
例如,如果有两个函数foo和bar,可以使用以下代码将它们映射到不同的键上:
```cpp
#include <iostream>
#include <map>
void foo() {
std::cout << "Hello from foo!" << std::endl;
}
void bar() {
std::cout << "Hello from bar!" << std::endl;
}
int main() {
std::map<std::string, void (*)()> func_map;
func_map["foo"] = foo;
func_map["bar"] = bar;
std::string func_name;
std::cout << "Enter function name (foo or bar): ";
std::cin >> func_name;
auto it = func_map.find(func_name);
if (it != func_map.end()) {
it->second();
} else {
std::cout << "Function not found!" << std::endl;
}
return 0;
}
```
在这个代码中,我们使用std::map容器来将函数映射到不同的键上。键的类型是std::string,值的类型是void (*)(),即指向不带参数的void函数的指针。
然后,我们在main函数中询问用户要调用哪个函数,通过键在map中查找相应的函数指针,并调用它。如果键不存在,我们就打印“Function not found!”的消息。
当用户输入“foo”时,输出将是“Hello from foo!”;当用户输入“bar”时,输出将是“Hello from bar!”。
阅读全文
相关推荐


















