C++ Lambda expressions, functions and algorithms

Lambda Expressions

Derived from Lisp

Previously for_each needs a function

Will use new C++11 idea - write an unnamed function in place - a lambda expression

#include<algorithm>
#include<vector>
#include<iostream>

using namespace std;

void incr(int &i){static int n=1; i=n++;}
void outvec(int i){cout << i << endl;}

int main(){
    vector <int> v(6);
    for_each(v.begin(), v.end(), incr);
    for_each(v.begin(), v.end(), outvec);
}

Unnamed function

[](int i){cout << i << endl;} // goes where the fuction object is required

[](int n){return n*5.5;} //double

//deduces the return value-no return void

[](int n)->int{return ++n;} //explicit

Read wikipedia about Lambda

 

Mutating Function

template<class Inputlter, class Outputlter>
Outputlter copy(InputIter b1, InputIter e1, OutputIter b2);

Copying algorithm over elements b1 to e1

Copy is placed starting at b2

Position returned is end of copy

posted @ 2019-01-23 21:32  王老吉味巧克力  阅读(96)  评论(0编辑  收藏  举报