C++等价于在python中传递lambda函数作为参数
C++ equivalent for passing a lambda function as an argument in 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
在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; })
相关文章:
- 可组合的lambda/std::函数与std::可选
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 如何将lambda作为模板类的成员函数参数
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 模板函数指针和lambda
- 两组使用lambda函数的大括号
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 在构造函数中使用 lambda 的 C++ 类
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- 为什么我不能在 constexpr lambda 函数中使用 std::tuple
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- C++:Lambda 函数指针转换的用例是什么?
- 将有状态的 lambda 传递到 C 样式函数中,而无需上下文参数
- std::映射服装比较函数和函数/lambda错误
- 在可移动类型的构造函数 lambda 中捕获此内容的安全使用
- 排序测试模板化函数 lambda:非法使用此类型作为表达式
- 将匿名函数(lambda)保存为函数类型变量
- 如何编写将自身作为回调传递的匿名函数/lambda