问题
- 编写一个lambda,接受两个int,返回它们的和.
- 编写一个lambda,捕获它所在函数的int,并接受一个int参数。lambda应该返回捕获的int和int参数的和.
源代码
1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /************************************************************************* > File Name: test.10.14.cpp > Author: puruidong > Mail: 1@w1520.com > Created Time: 2014年06月14日 ************************************************************************/ #include<iostream> using namespace std; /*************************************** 编写一个lambda,接受两个int,返回它们的和. **************************************************/ int main() { int a,b; cout << "输入两个数字[int]:" << endl; cin >> a >> b; auto f = [](int a,int b){return a+b;}; cout << "计算结果:\n" << f(a,b) << endl; return 0; } |
2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | /************************************************************************* > File Name: test.10.15.cpp > Author: puruidong > Mail: 1@w1520.com > Created Time: 2014年06月14日 ************************************************************************/ #include<iostream> using namespace std; /********************************** 编写一个lambda,捕获它所在函数的int,并接受一个int参数。lambda应该返回捕获的int和int参数的和. ************************************************/ int add(int a,int b) { auto re = [a](int b){ return a+b; }; return re(b); } int main() { int a,b; cout << "输入两个int:" << endl; cin >> a >> b; cout << "计算结果:" ; cout << add(a,b) << endl; return 0; } |
问题
使用lambda编写一个函数,输出大于等于指定参数的元素的值和数量.
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | /************************************************************************* > File Name: lambda2.cpp > Author: puruidong > Mail: 1@w1520.com > Created Time: 2014年06月13日 ************************************************************************/ #include<iostream> #include<vector> #include<algorithm> using namespace std; /**************************** -- 接受一个指定参数,匹配vector中大于等于此参数值的元素数量,并输出. *************************************/ void bis(vector<string> &vec,vector<string>::size_type sz) { sort(vec.begin(),vec.end());//排序. auto resdel= unique(vec.begin(),vec.end());//删除重复单词 vec.erase(resdel,vec.end()); stable_sort(vec.begin(),vec.end(),[](const string &a,const string &b){return a.size()<b.size();});//按长度排序,长度相同的维持字典序. auto reds = find_if(vec.begin(),vec.end(),[sz](const string &s){return s.size()>=sz;});//获取一个迭代器,指向第一个满足size()>=sz的元素. auto count = vec.end()-reds; cout << "总共有:" << count << "个大于等于" << sz << "的元素" << endl; cout << "传入的数值是:" << sz << "\n大于等于此值的元素如下:" << endl; for_each(reds,vec.end(),[](const string &s){cout << s << " " << endl;}); } int main() { vector<string> vec; string pa; cout << "根据传入的数值输出vector中大于等于此数值的元素:" << endl; while(cin >> pa) { vec.push_back(pa); } bis(vec,5); return 0; } |
《C++:lambda可调用表达式》上有1条评论