匿名函数和for_each用法
Posted music-liang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了匿名函数和for_each用法相关的知识,希望对你有一定的参考价值。
匿名函数,C++11的 for_each 用法
#include <iostream> #include <algorithm> #include "testClassA.h" using namespace std; void tiwce(int& elem) { elem = elem * 2; } // 不带参数,不带返回值 // [](){cout << 123 << ","; }; // []{cout << 123 << ","; }; // 不带参数,带返回值 // []()->(int){cout << 123 << ","; return 666; }; // 带参数,带返回值的 //[](int elem)->(int){cout << elem << ","; return 666; }; // 带参数,不带返回值, lamb 表达式 // [](int elem){cout << elem << ","; }; int main() { P px = { 77, 5 }; int values[] {1, 2, 3, 4, 5, 6, 7, 8}; // for_each(&values[0], &values[5], tiwce); // for_each(&values[0], &values[5], [](int& elem){elem = elem * 2; }); // for_each(&values[0], &values[5], [](int elem){cout << elem << ","; }); //for (auto v : values) //{ // cout << v << ", "; //} int x = 0; int y = 42; cout << "1111111111" << endl; auto qqq = [x, &y]{ std::cout << "X:" << x << endl; std::cout << "Y:" << y << endl; ++y; }; cout << "22222222" << endl; x = y = 77; cout << x << endl; cout << "333333" << endl; qqq(); qqq(); cout << "Final:" << "X:" << x << ",Y:" << y << endl; cout << endl; cout << "C++11 standard" << endl; system("pause"); return 0; }
以上是关于匿名函数和for_each用法的主要内容,如果未能解决你的问题,请参考以下文章
函数globals和locals用法, LEGB原则, 闭包函数 , 匿名函数