C++11添加了lambda函数的新功能,在使用过程中将匿名函数作为函数参数传递将会变得非常的简洁。在之前一般使用函数指针和函数符将函数作为参数传递给另外一个参数。
/** 匿名函数
* 1. lambda匿名函数离使用的位置最近,进行修改非常方便
* 2. 使用auto mod3 = [](int x) { return x % 3 == 0; }; 可以像常规函数一样使用匿名函数
* 3. 使用lambda函数用于接受函数指针或者函数符的函数将会非常简洁易于理解
* 4. 完整的表达式规范是[capture\](param) exception->ret{ body }
* 5. capture可以捕获在函数的可见域中的变量 [a, &b]按值捕获a 按引用捕获b []不捕获任何值
* 6. param为参数列表,需要与函数接受的函数参数类型一致, 如果没有参数可以省略
* 7. exception表示抛出何种异常,如果没有省略
* 8. ret在无法自动判别返回类型的时候,程序员手动指明
*/
lambda函数的使用示例:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
const long size1 = 39L;
const long size2 = 100 * size1;
const long size3 = 100 * size2;
bool f3(int x) {
return x % 3 == 0;
}
bool f13(int x) {
return x % 13 == 0;
}
int main() {
// 使用函数指针
std::vector<int> nums(size1);
std::srand(std::time(0));
std::generate(nums.begin(), nums.end(), std::rand);
std::cout << "sample size = " << size1 << '\n';
int count3 = std::count_if(nums.begin(), nums.end(), f3);
std::cout << "count of numbers divisible by 3: " << count3 << '\n';
int count13 = std::count_if(nums.begin(), nums.end(), f13);
std::cout << "count of numbers divisible by 13: " << count13 << '\n';
// 使用函数符 [接受的函数使用对象的f_mod(x).operator()方法]
class f_mod {
private:
int dv;
public:
f_mod(int d): dv(d) {}
bool operator()(int x) {
return x % dv == 0;
}
};
nums.resize(size2);
std::generate(nums.begin(), nums.end(), std::rand);
std::cout << "sample size = " << size2 << '\n';
count3 = std::count_if(nums.begin(), nums.end(), f_mod(3));
std::cout << "count of numbers divisible by 3: " << count3 << '\n';
count13 = std::count_if(nums.begin(), nums.end(), f_mod(13));
std::cout << "count of numbers divisible by 13: " << count13 << '\n';
// 使用Lambda匿名函数,使用[]代替了函数名,没有声明返回类型(根据return子句自动推断,
// 当推断存在二异性的时候需要手动添加返回值类型)
// [](double x)->double({ int y = x; return y - x; });
nums.resize(size3);
std::generate(nums.begin(), nums.end(), std::rand);
std::cout << "sample size = " << size3 << '\n';
count3 = std::count_if(nums.begin(), nums.end(), [](int x){ return x % 3 == 0; });
std::cout << "count of numbers divisible by 3: " << count3 << '\n';
count13 = std::count_if(nums.begin(), nums.end(), [](int x) { return x % 13 == 0; });
std::cout << "sample of number divisible by 13: " << count13 << '\n';
// 使用lambda函数捕获动态变量
count3 = count13 = 0;
std::for_each(nums.begin(), nums.end(), [&count3, &count13](int x) {
count3 += x % 3 == 0;
count13 += x % 13 == 0;
});
std::cout << "count of nums divisible by 3: " << count3 << '\n';
std::cout << "count of nums divisible by 13: " << count13 << '\n';
return 0;
}