fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. struct Even {
  6.  
  7. void operator() (int n)
  8. {
  9. std::cout << n;
  10.  
  11. if (n % 2 == 0) {
  12. std::cout << " is even " << std::endl;
  13. ++evenCount;
  14. }
  15. else {
  16. std::cout << " is odd " << std::endl;
  17. }
  18. }
  19.  
  20. // To use a single copy and preserve
  21. // value use static
  22. static int evenCount;
  23. };
  24.  
  25. int Even::evenCount = 0;
  26.  
  27. int main()
  28. {
  29. // Create a vector object that contains 10 elements.
  30. std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  31.  
  32. // Count the number of even numbers in the vector
  33.  
  34.  
  35. // Using function object
  36. for_each(v.begin(), v.end(), Even());
  37.  
  38. // Print the count of even numbers to the console.
  39. std::cout << "There are " << Even::evenCount
  40. << " even numbers in the vector." << std::endl;
  41.  
  42. // Using lambda function
  43. int evenCount = 0;
  44.  
  45. for_each(v.begin(), v.end(),
  46.  
  47. // The capture-list specifies what variables
  48. // the lamba expression can use from outside.
  49. [&evenCount] (int n)
  50. {
  51. std::cout << n;
  52.  
  53. if (n % 2 == 0) {
  54. std::cout << " is even " << std::endl;
  55. ++evenCount;
  56. }
  57. else {
  58. std::cout << " is odd " << std::endl;
  59. }
  60. }
  61. );
  62.  
  63. // Print the count of even numbers to the console.
  64. std::cout << "There are " << evenCount
  65. << " even numbers in the vector." << std::endl;
  66. }
  67.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
1 is odd 
2 is even 
3 is odd 
4 is even 
5 is odd 
6 is even 
7 is odd 
8 is even 
9 is odd 
10 is even 
There are 5 even numbers in the vector.
1 is odd 
2 is even 
3 is odd 
4 is even 
5 is odd 
6 is even 
7 is odd 
8 is even 
9 is odd 
10 is even 
There are 5 even numbers in the vector.