【问题标题】:Adding an array of functions and randomly selecting one of them [closed]添加一组函数并随机选择其中一个[关闭]
【发布时间】:2014-12-12 11:30:20
【问题描述】:

我一直在尝试寻找一种创建函数数组的方法。我使用 Xcode,每次尝试时都会提示我警告

函数样式转换或类型构造的预期“(”。

我不太确定该怎么做。这是一个代码示例。

//possibleResponses

int Responses[]{ //this is where the error is.

int possibleResponse1;
{
    cout << "Continue...\n";
    getline (cin, inputc);
}

int possibleResponse2 (0);
{
    cout << "Text" << inputb << ".\n";
    getline (cin, inputd);
}

为了澄清,我的程序可以给出二十种不同的可能响应。我想将它们放在一个数组中,然后随机化输出。如果有人可以帮助我,那就太好了(如果可能,添加示例代码,这样我会更好地学习),提前谢谢!

【问题讨论】:

    标签: c++ arrays xcode function compiler-errors


    【解决方案1】:

    我不确定您对发布的代码做了什么,但我确信它不会编译。我将尝试展示如何添加“一组函数并随机选择一个”。

    int function1() { ... } // implementation is irrelevant
    int function2(int x) { ... }
    int function3(char x) { ... }
    

    客户端代码:

    #include <functional>
    #include <vector>
    
    std::vector<std::function<int(void)>> functions; // all functions placed
                                                     // in here take no parameters
    
    functions.push_back(function1);
    functions.push_back( []() { return function2(190); } ); // adaptor functor, calling
                                                            // function2 with parameters
                                                            // the adaptor matches the
                                                            // signature of
                                                            // functions::value_type
    functions.push_back( []() { return function3('s'); } ); // same as above
    

    从序列中调用一个随机函数:

    #include <random>
    
    std::random_device rd;
    static std::mt19937 gen(rd()); // mersene twister
    std::uniform_int_distribution<> d(0, functions.size());
    auto itr = std::begin(functions);
    std::advance(itr, dis(gen)); // advance iterator by random number of positions
    
    (*itr)(); // call the functor
    

    或:

    #include <random>
    
    std::random_device rd;
    static std::mt19937 gen(rd()); // mersene twister
    std::uniform_int_distribution<> d(0, functions.size());
    auto index = dis(gen)); // get index in range [0, functions.size())
    
    functions[index]();
    

    为了保持代码干净,请考虑将响应函数放在命名空间中(至少):

    namespace responses {
        int function1() { ... } // implementation is irrelevant
        int function2(int x) { ... }
        int function3(char x) { ... }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-08
      • 2013-01-12
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      相关资源
      最近更新 更多