创建和回推函数向量

Creating and pushing back a vector of functions

本文关键字:函数 向量 创建      更新时间:2023-10-16

我想创建一个函数向量并"push_back"它,但不知道如何正确完成。谢谢,提前。这就是我到目前为止所拥有的:

    int a = 1;
    int b = 2;
    int function1()
    {
        return (a+b)*c;
    }
    typedef std::function<int> function1;
    typedef std::vector<function> functionsvector;

    functionvector.push_back(function1);

你不应该在这里使用typedef。这意味着您将这些类型别名为您指定的名称,而不是创建它们的实例。

您应该改为这样做:

//create a vector of functions which take no arguments and return an int
std::vector<std::function<int()>> functionvector {};
//implicitly converts the function pointer to a std::function<int()> and pushes
functionvector.push_back(function1);