ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c++ lambda学习举例

2022-08-20 20:31:19  阅读:146  来源: 互联网

标签:std cout int c++ 举例 using include 表达式 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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有