【问题标题】:accept strings to call functions [closed]接受字符串来调用函数[关闭]
【发布时间】:2014-06-16 21:16:51
【问题描述】:

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

void hello()
{
    cout<<"used as a greeting or to begin a telephone conversation.";
 }
void main()
{
    #define a b()
    char b[]="hello";
    a;

}

因此,在上面的代码中,例如有一些函数集,例如 hello(几乎有数千个),我希望用户输入一个字符串(字符数组),然后程序使用它来调用一个函数已经制定或定义。 就像上面的例子一样,hello 是由用户输入的,然后程序必须从那里调用函数。

我知道程序不对,但请耐心等待。 如果问题不够清楚,请发表评论,我会尽快回复。

【问题讨论】:

  • 您可以使用std::map&lt;std::string, std::function&lt;void()&gt;&gt;

标签: c++ string function


【解决方案1】:

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

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

Live demo

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

【讨论】:

  • 包括:&lt;functional&gt;, &lt;string&gt;, &lt;map&gt;
【解决方案2】:

以下可能会有所帮助:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 2022-01-24
    • 2017-11-22
    • 2017-03-03
    • 2012-01-16
    • 2019-12-14
    • 2013-05-05
    相关资源
    最近更新 更多