lambda1.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. // lambda1.cpp -- use captured variables
  2. #include <iostream>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <cmath>
  6. #include <ctime>
  7. const long Size = 390000L;
  8. int main()
  9. {
  10. using std::cout;
  11. std::vector<int> numbers(Size);
  12. std::srand(std::time(0));
  13. std::generate(numbers.begin(), numbers.end(), std::rand);
  14. cout << "Sample size = " << Size << '\n';
  15. // using lambdas
  16. int count3 = std::count_if(numbers.begin(), numbers.end(),
  17. [](int x){return x % 3 == 0;});
  18. cout << "Count of numbers divisible by 3: " << count3 << '\n';
  19. int count13 = 0;
  20. std::for_each(numbers.begin(), numbers.end(),
  21. [&count13](int x){count13 += x % 13 == 0;});
  22. cout << "Count of numbers divisible by 13: " << count13 << '\n';
  23. // using a single lambda
  24. count3 = count13 = 0;
  25. std::for_each(numbers.begin(), numbers.end(),
  26. [&](int x){count3 += x % 3 == 0; count13 += x % 13 == 0;});
  27. cout << "Count of numbers divisible by 3: " << count3 << '\n';
  28. cout << "Count of numbers divisible by 13: " << count13 << '\n';
  29. // std::cin.get();
  30. return 0;
  31. }