lambda0.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // lambda0.cpp -- using lambda expressions
  2. #include <iostream>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <cmath>
  6. #include <ctime>
  7. const long Size1 = 39L;
  8. const long Size2 = 100*Size1;
  9. const long Size3 = 100*Size2;
  10. bool f3(int x) {return x % 3 == 0;}
  11. bool f13(int x) {return x % 13 == 0;}
  12. int main()
  13. {
  14. using std::cout;
  15. std::vector<int> numbers(Size1);
  16. std::srand(std::time(0));
  17. std::generate(numbers.begin(), numbers.end(), std::rand);
  18. // using function pointers
  19. cout << "Sample size = " << Size1 << '\n';
  20. int count3 = std::count_if(numbers.begin(), numbers.end(), f3);
  21. cout << "Count of numbers divisible by 3: " << count3 << '\n';
  22. int count13 = std::count_if(numbers.begin(), numbers.end(), f13);
  23. cout << "Count of numbers divisible by 13: " << count13 << "\n\n";
  24. // increase number of numbers
  25. numbers.resize(Size2);
  26. std::generate(numbers.begin(), numbers.end(), std::rand);
  27. cout << "Sample size = " << Size2 << '\n';
  28. // using a functor
  29. class f_mod
  30. {
  31. private:
  32. int dv;
  33. public:
  34. f_mod(int d = 1) : dv(d) {}
  35. bool operator()(int x) {return x % dv == 0;}
  36. };
  37. count3 = std::count_if(numbers.begin(), numbers.end(), f_mod(3));
  38. cout << "Count of numbers divisible by 3: " << count3 << '\n';
  39. count13 = std::count_if(numbers.begin(), numbers.end(), f_mod(13));
  40. cout << "Count of numbers divisible by 13: " << count13 << "\n\n";
  41. // increase number of numbers again
  42. numbers.resize(Size3);
  43. std::generate(numbers.begin(), numbers.end(), std::rand);
  44. cout << "Sample size = " << Size3 << '\n';
  45. // using lambdas
  46. count3 = std::count_if(numbers.begin(), numbers.end(),
  47. [](int x){return x % 3 == 0;});
  48. cout << "Count of numbers divisible by 3: " << count3 << '\n';
  49. count13 = std::count_if(numbers.begin(), numbers.end(),
  50. [](int x){return x % 13 == 0;});
  51. cout << "Count of numbers divisible by 13: " << count13 << '\n';
  52. // std::cin.get();
  53. return 0;
  54. }