Lambda in C++

按照对象的某个属性排序,是一种常见的排序需求。
在c++11之前,是这么做的:

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
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
class dorian{
public:
int m_a;
int m_b;
dorian()=default;
dorian(int a, int b):m_a(a),m_b(b){}
};
void printVec(vector<dorian> vec, string title){
cout << left << setw(20) << title;
for(auto i : vec)
cout << "(" << i.m_a << ", " << i.m_b << ") ";
cout << endl;
}
int sort_m_a(dorian c1, dorian c2){
return c1.m_a < c2.m_a;
}
int sort_m_b(dorian c1, dorian c2){
return c1.m_b < c2.m_b;
}
int main(){
vector<dorian> vec;
vec.push_back(dorian(1,4));
vec.push_back(dorian(3,2));
vec.push_back(dorian(4,1));
vec.push_back(dorian(2,3));

printVec(vec,"[Original]");

sort(vec.begin(),vec.end(),sort_m_a);
printVec(vec,"[Sorted by m_a]");

sort(vec.begin(),vec.end(),sort_m_b);
printVec(vec,"[Sorted by m_b]");
}


//执行打印如下
[Original] (1, 4) (3, 2) (4, 1) (2, 3)
[Sorted by m_a] (1, 4) (2, 3) (3, 2) (4, 1)
[Sorted by m_b] (4, 1) (3, 2) (2, 3) (1, 4)

从C++11开始,我们可以使用Lambda表达式,消灭sort_m_a,sort_m_b这两个函数

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
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
class dorian{
public:
int m_a;
int m_b;
dorian()=default;
dorian(int a, int b):m_a(a),m_b(b){}
};
void printVec(vector<dorian> vec, string title){
cout << left << setw(20) << title;
for(auto i : vec)
cout << "(" << i.m_a << ", " << i.m_b << ") ";
cout << endl;
}
int main(){
vector<dorian> vec;
vec.push_back(dorian(1,4));
vec.push_back(dorian(3,2));
vec.push_back(dorian(4,1));
vec.push_back(dorian(2,3));

printVec(vec,"[Original]");

sort(vec.begin(),vec.end(),[](dorian c1,dorian c2)->int{return c1.m_a < c2.m_a;});
printVec(vec,"[Sorted by m_a]");

sort(vec.begin(),vec.end(),[](dorian c1,dorian c2)->int{return c1.m_b < c2.m_b;});
printVec(vec,"[Sorted by m_b]");
}

//执行打印如下
[Original] (1, 4) (3, 2) (4, 1) (2, 3)
[Sorted by m_a] (1, 4) (2, 3) (3, 2) (4, 1)
[Sorted by m_b] (4, 1) (3, 2) (2, 3) (1, 4)

当然 lambda也可以先定义,方便多处使用

1
2
3
4
5
sort(vec.begin(),vec.end(),[](dorian c1,dorian c2)->int{return c1.m_a < c2.m_a;});
可以改为:

auto func = [](dorian c1,dorian c2)->int{return c1.m_a < c2.m_a;};
sort(vec.begin(),vec.end(),func);

联合for_each和lambda,消灭传统for循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main(){
vector<int> vec;
vec.push_back(0);
vec.push_back(3);
vec.push_back(6);
vec.push_back(8);
int count = 0;
for_each(vec.begin(), vec.end(), [&](int a){ if(a>5) { cout << a << endl; count++; } });
cout << "Total count: "<< count <<endl;

}

以上。