深入学习c++--lambda函数
Posted douzujun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了深入学习c++--lambda函数相关的知识,希望对你有一定的参考价值。
1. 简单使用
#include <iostream> #include <functional> using namespace std; struct Print { void operator()(int a, int b, int c) const { cout << "a " << a << " b " << b << " c " << c << endl; } }; void printInfo(int a, int b, int c) { cout << "a " << a << " b " << b << " c " << c << endl; } template<typename T1, typename T2, typename T3> void templatePrint(T1 a, T2 b, T3 c) { cout << "a " << a << " b " << b << " c " << c << endl; } struct TemplatePrint { template<typename T1, typename T2, typename T3> void operator()(T1 a, T2 b, T3 c) const { cout << "a " << a << " b " << b << " c " << c << endl; } }; template<typename Func> void printUserFunc(Func func, int a, int b, int c) { func(a, b, c); } int main() { Print printUserClass; TemplatePrint printUserTempClass; printInfo(1, 2, 3); templatePrint(11, 22, 33); printUserClass(111, 222, 333); printUserTempClass(1111, 2222, 3333); // lambda c++ auto local = [](int a, int b, int c) { cout << "a " << a << " b " << b << " c " << c << endl; }; local(123, 123, 123); printUserFunc(local, 121, 212, 313); //lambda c++ printUserFunc([](int a, int b, int c) { cout << "a " << a << " b " << b << " c " << c << endl; }, 121, 212, 313); // 值拷贝 int a = 23, b = 34, c = 45; auto local2 = [a, b, c] () { cout << "a " << a << " b " << b << " c " << c << endl; }; local2(); //传引用 auto local3 = [&] () { // &:外部引用 和 =: 外部拷贝 cout << "a " << a << " b " << b << " c " << c << endl; }; local3(); return 0; }
以上是关于深入学习c++--lambda函数的主要内容,如果未能解决你的问题,请参考以下文章