[capture list] (params list) mutable exception-> return type { function body }
表达式中各个参数的含义如下:
[capture list]:外部变量列表 (表示外部传进来的数值)
(params list):形参列表 (比如用for_each传进来的数值)
mutable:表示能不能修改捕获的变量 (可省略)
exception:异常设定 (可省略)
return type:返回类型 (可省略)
function body:函数体
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
void myPrintf(int elem)
{
cout << elem << " ";
}
int main()
{
vector<int> vec(5);
int i = 1;
int num = 0;
cout << "-----------通过外部参数给vec赋值,num改变,i不改变----------" << endl;
generate(vec.begin(), vec.end(), [i, &num]() {
num = i * i + num;
return num;
});
cout << "-----------值传递和引用传递的区别----------" << endl;
cout << "i = " << i << " num = " << num << endl;
cout << "-----------打印vec中的值----------" << endl;
for_each(vec.begin(), vec.end(), [](int i) {
cout << i<<" ";
});
cout << endl;
cout << "-----------传递外部变量和形参,引用传递则改变外部变量----------" << endl;
int total = 0;
for_each(vec.begin(), vec.end(), [&total](int i) {
total += i;
});
cout << "total = " << total << endl;
cout << "-----------形参以值传递方式,实参的数值不改变----------" << endl;
int num1 = 10;
int num2 = 5;
for_each(vec.begin(), vec.end(), [=](int x) {
x = x * num1 + num2;
cout << "x = " << x << endl;
});
//vec中的数值未改变
for_each(vec.begin(), vec.end(), myPrintf);//可用myPrintf函数来打印输出,也可用lambda来打印
cout << endl;
cout << "-----------形参以引用传递方式,实参的数值会改变----------" << endl;
for_each(vec.begin(), vec.end(), [=](int &x) {
x = x * num1 + num2;
cout << "x = " << x << endl;
});
//vec中的数值改变
for_each(vec.begin(), vec.end(), myPrintf);
cout << endl;
cout << "-----------删除digits中等于blacklist的数值----------" << endl;
std::set<int> blacklist = { 7, 8, 9 };
std::vector<int> digits = { 3, 9, 1, 8, 4, 7, 1 };
digits.erase(std::remove_if(digits.begin(), digits.end(), [blacklist](int i) {
return blacklist.find(i) != blacklist.end();
}),
digits.end());
for (auto i : digits)
cout << i << endl;
}