如何用函数填充向量?

时间:2020-03-29 04:29:03

标签: c++ function vector using func

#include <iostream>
#include<string>
#include<vector>
#include<functional>
using namespace std;
void straightLineMethod();
void unitsOfActivity();
void decliningMethod();

int main()
{
    using func = std::function<void()>;
    string inputMethod;
    string depreciation[3] = { "straight line","units of activity","declining" };
    std::vector<func> functions;
    functions.push_back(straightLineMethod);
    functions.push_back(unitsOfActivity);
    functions.push_back(decliningMethod);
    cout << " Enter the method of depreciation you're using: " << depreciation[0] << ", " << depreciation[1] << " , or " << depreciation[2] << endl;
    cin.ignore();
    getline(cin, inputMethod);
    for (int i = 0; i <functions.size() ; i++) {
        while(inputMethod == depreciation[i])
        {
            functions[i]();
        }
}

我尝试研究答案并了解了使用std::function的知识,但我并不完全了解它的作用。在网上很难找到与此问题相关的答案。本质上,我想要的是将三个函数放在向量中,将用户输入与字符串数组进行比较,然后使用数组中的索引来使用向量中的相关索引来调用函数。对我来说,这似乎是个好主意,但失败了。在这种情况下,使用.push_back尝试填充矢量给了我

E0304 error:  no instance of overloaded function matches the argument list. 

Edit: Specifically, I dont know what the syntax: using func= std::function<void()> is actually doing. I just added it to the code to try to get it to work , thats why my understanding is limited in troubleshooting here.

Edit: the E0304 error is fixed by correcting the syntax to reference the function instead of calling it. And i changed functions[i] to functions[i]() to call the functions, although it is still not working.

1 个答案:

答案 0 :(得分:0)

好像您混淆了函数调用语法,并传递了一个实际的(对a的引用)函数。在您的functions.push_back(functionNameHere)中,删除内部的(),您不想调用该函数,而是想将函数本身推入向量。另一方面,您的functions[i]应该是functions[i](),因为您实际上是在调用函数。

例如,这肯定有效:

void testMethod() 
{
    cout << "test method has been called\n";
}

int main()
{
    using func = std::function<void()>;
    std::vector<func> functions;
    functions.push_back(testMethod);
    functions[0]();
}

看到它在这里运行-http://cpp.sh/2xvnw