lambda1.cpp
来源: 探讨 C++ 新标准
点击上方按钮打开代码编辑器和可视化视图
⚠️ 交互式运行提示
为了防止网页挂起,所有 cin 输入语句已被自动注释。请直接在代码编辑器中修改变量的值来进行测试。
书本配套例题
原始代码预览
// lambda1.cpp -- use captured variables
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <ctime>
const long Size = 390000L;
int main()
{
using std::cout;
std::vector<int> numbers(Size);
std::srand(std::time(0));
std::generate(numbers.begin(), numbers.end(), std::rand);
cout << "Sample size = " << Size << '\n';
// using lambdas
int count3 = std::count_if(numbers.begin(), numbers.end(),
[](int x){return x % 3 == 0;});
cout << "Count of numbers divisible by 3: " << count3 << '\n';
int count13 = 0;
std::for_each(numbers.begin(), numbers.end(),
[&count13](int x){count13 += x % 13 == 0;});
cout << "Count of numbers divisible by 13: " << count13 << '\n';
// using a single lambda
count3 = count13 = 0;
std::for_each(numbers.begin(), numbers.end(),
[&](int x){count3 += x % 3 == 0; count13 += x % 13 == 0;});
cout << "Count of numbers divisible by 3: " << count3 << '\n';
cout << "Count of numbers divisible by 13: " << count13 << '\n';
// std::cin.get();
return 0;
}
运行结果 / 调试信息
等待编译...
Graph loading...
0 / 0