C++ lambda表达式

来源:互联网 发布:ieterm mac 编辑:程序博客网 时间:2024/05/11 00:50

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](conststring &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;
}
0 0