C++等价于在python中传递lambda函数作为参数

C++ equivalent for passing a lambda function as an argument in python

本文关键字:函数 lambda 参数 等价于 python C++      更新时间:2023-10-16

在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

在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 bday) {
    employee_vector found;
    found = getEmployeeByCondition([](Employee e) {return e.birthday == bday;});
    return found;
}

现在的问题是,我显然不能在getEmployeeByBirthday的lambda函数中使用bday,因为它是一个局部变量。

是的,您可以将lambda传递给函数。

您可以使用模板:

template <typename Func>
void foo (Func f) {
    f();
}
foo([]{ std::cout << "Hello"; });

std::function:

void foo (std::function<void()> f) {
    f();
}
foo([]{ std::cout << "Hello"; });

如果要在std::vector中搜索满足某些条件的对象,可以使用std::find_if:

std::find_if(my_vec.begin(), my_vec.end(), 
             [](auto& el) { return /*does this fulfil criteria?*/; });

至于getThingsByCondition,它可能看起来像这样:

template <typename T, typename...Ts, typename Func>
std::vector<std::reference_wrapper<T>>
filter(std::vector<T,Ts...>& container, const Func& func) {
    std::vector<std::reference_wrapper<T>> ret;
    for (auto& el : container) {
        if (func(el)) ret.push_back(std::ref(el));   
    }
    return ret;
}

这当然可以改进为使用不同的容器等。而且它几乎肯定不会适用于std::vector<bool>

您可以像一样设计getThingsByCondition

using things_vec = std::vector<std::reference_wrapper<Thing>>;
things_vec getThingsByCondition(std::function<bool(const Thing&)> condition);

您可以使用类似lambda的调用getThingsByCondition函数

auto things = getThingsByCondition([](const Thing& thing) { return thing.attr1 == 1; })