fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <iterator>
  5.  
  6. class Object
  7. {
  8. public:
  9. Object() { modify = 0; };
  10. int modify;
  11. };
  12.  
  13. std::ostream& operator<<(std::ostream& stream, const Object& object)
  14. {
  15. stream << object.modify;
  16. return stream;
  17. }
  18.  
  19. struct Functor
  20. {
  21. Functor(int new_value)
  22. {
  23. _new_value = new_value;
  24. }
  25.  
  26. void operator()(Object& object)
  27. {
  28. object.modify = _new_value;
  29. }
  30.  
  31. int _new_value;
  32. };
  33.  
  34. void function_modify(Object& object)
  35. {
  36. object.modify = 2;
  37. }
  38.  
  39. int main() {
  40. std::vector<Object> objects(10);
  41.  
  42. std::cout << "Initial vector" << std::endl;
  43. std::copy(objects.begin(), objects.end(), std::ostream_iterator<Object>(std::cout, ", "));
  44. std::cout << std::endl;
  45.  
  46. std::for_each(objects.begin(), objects.end(), Functor(1));
  47.  
  48. std::cout << "for_each Functor" << std::endl;
  49. std::copy(objects.begin(), objects.end(), std::ostream_iterator<Object>(std::cout, ", "));
  50. std::cout << std::endl;
  51.  
  52. std::for_each(objects.begin(), objects.end(), function_modify);
  53.  
  54. std::cout << "for_each function" << std::endl;
  55. std::copy(objects.begin(), objects.end(), std::ostream_iterator<Object>(std::cout, ", "));
  56. std::cout << std::endl;
  57.  
  58. std::for_each(objects.begin(), objects.end(), [](Object& object) { object.modify = 3; } );
  59.  
  60. std::cout << "for_each lambda" << std::endl;
  61. std::copy(objects.begin(), objects.end(), std::ostream_iterator<Object>(std::cout, ", "));
  62. std::cout << std::endl;
  63.  
  64. for (auto& object: objects) { object.modify = 4; }
  65.  
  66. std::cout << "for" << std::endl;
  67. std::copy(objects.begin(), objects.end(), std::ostream_iterator<Object>(std::cout, ", "));
  68. std::cout << std::endl;
  69.  
  70. return 0;
  71. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Initial vector
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
for_each Functor
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
for_each function
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 
for_each lambda
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 
for
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,