如何用函数填充向量


#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.

看起来您混淆了函数调用语法,并传递了一个实际的(对一个(函数。在functions.push_back(functionNameHere)中移除内部(),您不想调用该函数,而是想将函数本身推送到向量。从另一方面来说,您的functions[i]应该是functions[i](),因为在这里您实际上是在调用函数。

例如,这肯定有效:

void testMethod() 
{
cout << "test method has been calledn";
}
int main()
{
using func = std::function<void()>;
std::vector<func> functions;
functions.push_back(testMethod);
functions[0]();
}

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

最新更新