小编blu*_*bbi的帖子

C++相当于将一个lambda函数作为参数传递给python

在python中,您可以将lambda函数作为参数传递,如下所示:

class Thing(object):
    def __init__(self, a1, a2):
        self.attr1 = a1
        self.attr2 = a2

class ThingList(object):
    def __init__(self):
        self.things = [Thing(1,2), Thing(3,4), Thing(1,4)]

    def getThingsByCondition(self, condition):
        thingsFound = []
        for thing in self.things:
            if condition(thing):
                thingsFound.append(thing)
        return thingsFound

things = tl.getThingsByCondition(lambda thing: thing.attr1==1)
print things
Run Code Online (Sandbox Code Playgroud)

有没有办法在C++中做类似的事情?我需要这样做,因为我想在vector对象中搜索满足特定条件的对象.


好吧,我试着像这样解决它:我应该提到我在向量中管理的"事物"是员工,我想找到满足某些条件的员工.

employee_vector getEmployeeByCondition(function<bool(const Employee&)> condition) {
    employee_vector foundEmployees;
    for (int i = 0; i < employees.size(); i++) {
        Employee e = employees.at(i);
        if (condition(e)) {
            foundEmployees.push_back(e);
        }
    }
    return foundEmployees;
}

employee_vector getEmployeeByBirthday(Date …
Run Code Online (Sandbox Code Playgroud)

c++ python lambda function conditional-statements

1
推荐指数
1
解决办法
566
查看次数

标签 统计

c++ ×1

conditional-statements ×1

function ×1

lambda ×1

python ×1