You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中向emplace_back传递Lambda与vector构造Monkey类报错

解决C++中vector emplace_back传递Lambda参数的问题

第一步:正确定义Monkey类

你需要确保Monkey类的构造函数用std::function接收Lambda表达式——Lambda的类型是匿名的,无法直接作为固定类型参数传递。示例定义如下:

#include <vector>
#include <functional>

class Monkey {
private:
    std::vector<int> heldItems;
    std::function<int(int)> operation;
    std::function<int(int)> test;

public:
    // 构造函数:接收物品列表、操作函数、测试函数
    Monkey(std::vector<int> items, std::function<int(int)> op, std::function<int(int)> t)
        : heldItems(std::move(items)), operation(std::move(op)), test(std::move(t)) {}

    // 可选:验证用的物品打印方法
    void printItems() const {
        for (int item : heldItems) {
            std::cout << item << " ";
        }
        std::cout << "\n";
    }

    // 可选:执行操作的方法
    int doOperation(int item) const {
        return operation(item);
    }

    // 可选:执行测试的方法
    int doTest(int item) const {
        return test(item);
    }
};

第二步:main函数中正确使用emplace_back

现在可以直接向emplace_back传递参数(初始化vector时用大括号即可),以下是符合你需求的写法:

#include <iostream>

int main() {
    std::vector<Monkey> monkeyList;

    // 插入第一个Monkey对象
    monkeyList.emplace_back(
        std::vector<int>{79, 98},  // 持有物品列表
        [](int old) { return old * 19; },  // 乘19的操作Lambda
        [](int worry) { return (worry % 23 == 0) ? 2 : 3; }  // 模23判断的测试Lambda
    );

    // 验证结果
    Monkey& firstMonkey = monkeyList[0];
    std::cout << "第一个猴子的物品:";
    firstMonkey.printItems();
    std::cout << "物品79执行操作后的值:" << firstMonkey.doOperation(79) << "\n";
    std::cout << "物品79测试后返回的猴子编号:" << firstMonkey.doTest(79) << "\n";
    std::cout << "物品98测试后返回的猴子编号:" << firstMonkey.doTest(98) << "\n";

    return 0;
}

你的写法报错的原因

  • 原因1:如果Monkey构造函数没有用std::function,而是直接用Lambda的匿名类型作为参数,编译器无法匹配emplace_back的参数(每个Lambda的类型都是唯一的)。
  • 原因2:如果错误地用双层大括号包裹所有参数(比如monkeyList.emplace_back({...})),编译器会把大括号内容解析为Monkey的初始化列表,而非构造函数的三个独立参数。

额外提示

  • 用std::move转移vector和std::function的所有权,能避免不必要的拷贝,提升性能。
  • 如果需要捕获外部变量,Lambda可以添加捕获列表(比如[&](int old) {...}),但要保证捕获的变量生命周期长于Monkey对象。

内容的提问来源于stack exchange,提问作者CodeoftheWarrior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 16:55:18