c++将lambda和vector传递给emplace_back作为自定义类构造函数


#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;
}

如果你想知道,这是一个解决方案,我正在为代码的出现而不是任何类型的编程任务。

我面临的问题是,我想在我的主要方法中创建一个猴子对象的向量。在我看来,我应该能够将参数传递给Monkey类构造函数(vector, lambda, lambda)到vector类的emplace_back函数。每当我尝试上面的代码,我得到以下错误:

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; });

如果我将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]是一个对象,heldItems =两个int的向量,79和98,一个lambda的操作函数,它接受一个int并返回19 *那个int,如果一个int的模是23或3,则返回2。相对较新的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}可以是任何东西,所以编译器不知道它是什么,也不允许猜测。

最新更新