在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)