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

blu*_*bbi 1 c++ python lambda function conditional-statements

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

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

Tar*_*ama 6

是的,你可以将lambda传递给函数.

您可以使用模板:

template <typename Func>
void foo (Func f) {
    f();
}

foo([]{ std::cout << "Hello"; });
Run Code Online (Sandbox Code Playgroud)

或者std::function:

void foo (std::function<void()> f) {
    f();
}

foo([]{ std::cout << "Hello"; });
Run Code Online (Sandbox Code Playgroud)

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

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

至于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;
}
Run Code Online (Sandbox Code Playgroud)

这肯定可以改进,以适应不同的容器等.它几乎肯定不会工作std::vector<bool>.