编程语言
首页 > 编程语言> > c++ lambda学习举例

c++ lambda学习举例

作者:互联网

#include <iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<ctime>
using std::cout;
using std::vector;
using std::srand;
using std::time;
using std::generate;
using std::endl;
using std::count_if;
using std::for_each;
using std::rand;
const long Size = 390000L;
int main()
{
    std::cout << "Hello World!\n";
    vector<int> numbers(Size);
    srand(time(0));
    generate(numbers.begin(), numbers.end(), rand);
    cout << "Sample Size=" << Size << endl;
    int m = 3;
    int count3 = count_if(numbers.begin(), numbers.end(), [m](int x) { return x % m == 0; });

    cout << "mode by 3==0's count=" << count3 << endl;
    int count13 = count_if(numbers.begin(), numbers.end(), [](int x)->bool {return x % 13 == 0; });
    cout << "mode by 13==0's count=" << count13 << endl;
    count3 = 0;
    count13 = 0;
    cout << "=====================\n";
    for_each(numbers.begin(), numbers.end(), [&count3, &count13](int x) {count3 += x % 3 == 0; count13 += x % 13 == 0;  });
    cout << "mode by 3==0's count=" << count3 << endl;
    cout << "mode by 13==0's count=" << count13 << endl;
    int* p1 = new int(0);
    int* p2 = new int(0);
    cout << "=====================\n";
    for_each(numbers.begin(), numbers.end(), [=](int x) {*p1 += x % 3 == 0; *p2 += x % 13 == 0;  });
    cout << "mode by 3==0's count=" << *p1 << endl;
    cout << "mode by 13==0's count=" << *p2 << endl;
    delete p1;
    delete p2;

    int* p3= new int[2];
    p3[0] = 0;
    p3[1] = 0;
    cout << "=====================\n";
    for_each(numbers.begin(), numbers.end(), [=](int x) {*p3+= x % 3 == 0; p3[1] += x % 13 == 0;  });
    cout << "mode by 3==0's count=" << *p3 << endl;
    cout << "mode by 13==0's count=" << p3[1] << endl;
    delete[]p3;

}
在lambda中 返回类型可以根据 函数体的返回值自动确定。 也可以[](int x)->bool这样明确指出来。 返回为void 可以不写。 [=],表示表达式内部可访问外部的所有动态变量,指针 new什么创建的变量。 [&count3],表示访问count3的引用,没有创建副本,这样可以给count3赋值。 int m=3; [m] (int x) { return x % m == 0; },这种不可以在表达式内部赋值,只在表达式里做只读变量。 lambda 省略了函数名用索引代替,入参有的话还是需要要写类型 比如 int x。 需要特定访问符号才能访问到表达式外部的变量。

标签:std,cout,int,c++,举例,using,include,表达式,lambda
来源: https://www.cnblogs.com/HelloQLQ/p/16608529.html