[英]C++ passing lambdas and vectors to emplace_back for custom class constructor
#include <iostream>
#include <fstream>
#include <functional>
#include <vector>
class Monkey
{
public:
int itemsProcessed{0};
std::vector<int> heldItems;
std::function<int(int)> operationFunction;
std::function<int(int)> testFunction;
Monkey(std::vector<int> sI, std::function<int(int)> oF, std::function<int(int)> tF)
{
heldItems = sI;
operationFunction = oF;
testFunction = tF;
}
void addItem(int item)
{
heldItems.push_back(item);
}
std::vector<std::pair<int, int>> processItems()
{
std::vector<std::pair<int, int>> redistributedItems;
for (auto i : heldItems)
{
int adjusted = operationFunction(i);
// Divide by 3 after monkey doesn't break it. Floor is applied by default for int division
adjusted /= 3;
int toMonkey = testFunction(adjusted);
redistributedItems.emplace_back(toMonkey, adjusted);
}
return redistributedItems;
}
};
int main(int argc, char *argv[])
{
std::vector<Monkey> monkeyList;
monkeyList.emplace_back(
{79, 98}, [](int a) -> int
{ return a * 19; },
[](int a) -> int
{ return a % 23 ? 2 : 3; });
return EXIT_SUCCESS;
}
如果您想知道,这是我正在为代码的出现而不是任何类型的编程任务而努力的解决方案。
我面临的问题是我想在我的 main 方法中创建一个 Monkey 对象的向量。 在我看来,我应该能够将 arguments 传递给 Monkey class 构造函数(向量,lambda,lambda)到向量 class 的 emplace_back function。每当我尝试上面的代码时,我都会收到以下错误:
error: no matching function for call to 'std::vector<Monkey>::emplace_back(<brace-enclosed initializer list>, main(int, char**)::<lambda(int)>, main(int, char**)::<lambda(int)>)'
41 | monkeyList.emplace_back(
| ~~~~~~~~~~~~~~~~~~~~~~~^
42 | {79, 98}, [](int a) -> int
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
43 | { return a * 19; },
| ~~~~~~~~~~~~~~~~~~~
44 | [](int a) -> int
| ~~~~~~~~~~~~~~~~
45 | { return a % 23 ? 2 : 3; });
如果我用大括号将 arguments 包装到 emplace_back 以使用大括号初始化,我会收到以下错误:
error: no matching function for call to 'std::vector<Monkey>::emplace_back(<brace-enclosed initializer list>)'
42 | monkeyList.emplace_back({{79, 98}, [](int a)
| ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~
43 | { return a * 19; },
| ~~~~~~~~~~~~~~~~~~~
44 | [](int a)
| ~~~~~~~~~
45 | { return a % 23 ? 2 : 3; }});
是什么赋予了? 我希望 monkeyList[0] 是一个 object,其中 heldItems = 两个整数的向量,79 和 98,一个 lambada 的 operationFunction,它接受一个 int 并返回 19 * 那个 int,以及一个 lambda,如果模数为一个 int 是 23 或 3 否则。 C++ 相对较新,因此不胜感激。 谢谢。
问题是emplace_back
在传递时不知道{79, 98}
的类型。 所以你必须指定它是一个std::vector<int>
。
monkeyList.emplace_back(
std::vector<int>{79, 98}, [](int a) -> int
{ return a * 19; },
[](int a) -> int
{ return a % 23 ? 2 : 3; });
原因是因为emplace_back使用的是模板参数,而{79, 98}
可以是任何东西,所以编译器不知道它是什么,也不允许猜测。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.