接受字符串来调用函数

accept strings to call functions

本文关键字:调用 函数 字符串      更新时间:2023-10-16

在我开始之前,我知道这个问题对你来说可能很荒谬,但请耐心等待我。

void hello()
{
    cout<<"used as a greeting or to begin a telephone conversation.";
 }
void main()
{
    #define a b()
    char b[]="hello";
    a;
}
因此,在上面的代码中,例如有一些函数集,如hello(几乎有数千个)和i希望用户输入一个字符串(字符数组),然后程序使用它来调用已经创建或定义的函数。就像上面的例子一样,hello是由用户输入的,然后程序必须从那里调用函数。

我知道这个程序不对,但是请耐心听我说。如果你的问题不够清楚,请留下评论,我会尽快回复你。

您可以使用std::functionstd::map将字符串映射到函数:

std::map<std::string, std::function<void()>> map;
map["hello"] = hello;

现场演示

然后通过std::map::find搜索用户在map中输入的内容。

以下内容可能有所帮助:

#include <iostream>
#include <map>
#include <string>
#include <functional>
void hello_world() { std::cout << "hello world" << std::endl; }
void question() { std::cout << "The answer is 42" << std::endl; }
int main()
{
    bool finish = false;
    std::map<std::string, std::function<void()>> m = {
        {"hello", hello_world},
        {"question", question},
        {"exit", [&finish](){ finish = true; }},
    };
    while (!finish) {
        std::string input;
        std::cin >> input;
        auto it = m.find(input);
        if (it == m.end()) {
            std::cout << "the known input are" << std::endl;
            for (auto it : m) {
                std::cout << it.first << std::endl;
            }
        } else {
            it->second();
        }
    }
    return 0;
}