C++ lambda表达式

lambda表达式

一个lambda表达式表示一个可调用的代码单元。我们可以将其理解为一个未命名的内联函数。一个lambda表达式具有一个返回类型、一个参数列表、一个函数体。

但与函数不同,lambda表达式可定义在函数内部。一个lambda表达式具有如下形式:

[capture list] (parameter list) -> return type  { function body }

与普通函数不同,lambda表达式必须使用尾置返回来指定返回类型。

何为尾置返回类型:

尾置返回类型跟在形参列表后面并以一个 -> 符号开头。为了表示函数真正的返回类型,我们在本应该出现返回类型的地方放置一盒auto:

//func接受一个int类型的实参,返回一个指针,该指针指向一个具有10个整形数的数组
auto func(int i) -> int (*)[10];

下面来一个应用的例子

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
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using  namespace  std;
 
class  Solution
{
public :
     void  biggies(vector &words, vector::size_type sz)
     {
         //按字典顺序排序
         sort(words.begin(),words.end());
 
         //把重复部分置后
         auto end_unique = unique(words.begin(),words.end());
 
         //删除重复部分
         words.erase(end_unique,words.end());
 
         //按长度稳定排序(保持原有等长顺序)
         stable_sort(words.begin(), words.end(), []( const  string &a,  const  string &b){  return  a.size() < b.size(); });      
         //获取第一个指向大于sz的元素的迭代器      
         auto it = find_if(words.begin(), words.end(), [sz]( const string &str){  return  str.size() > sz; });
 
         //计算满足size大于sz的数目
         auto count = words.end() - it;
         cout << count << make_plural(count,  " word" "s" ) <<  " of length "  << sz <<  " or longer."  << endl;
 
         //输出长度大于sz的串
         for_each(it, words.end(), []( const  string &str){ cout << str <<  " " ; });    } 
 
         string make_plural( int  num, string word, string s)  
        
                 return  num > 1 ? word + s : word;
         }
 
     static  bool  isShorter( const  string &str1,  const  string &str2)
     {
         return  (str1.size() < str2.size());
     }
 
};
 
int  main( void )
{
     vector vec_str = { "HABCD" , "CDF" , "XYtrZ" , "UVWXY" , "LUOPMN" , "PLOPQ" , "RST" };
 
     Solution s;
 
     vector::size_type sz = 4;
 
     s.biggies(vec_str,sz);
 
     system ( "pause" );
     return  0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值