c++ lambda学习举例

2022/8/22 1:55:34

本文主要是介绍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。 需要特定访问符号才能访问到表达式外部的变量。

这篇关于c++ lambda学习举例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程