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。
需要特定訪問符號才能訪問到表達式外部的變量。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章