#include <iostream> #include <vector> #include <algorithm> #include <iterator> class Object { public: Object() { modify = 0; }; int modify; }; std::ostream& operator<<(std::ostream& stream, const Object& object) { stream << object.modify; return stream; } struct Functor { Functor(int new_value) { _new_value = new_value; } void operator()(Object& object) { object.modify = _new_value; } int _new_value; }; void function_modify(Object& object) { object.modify = 2; } int main() { std::vector<Object> objects(10); std::cout << "Initial vector" << std::endl; std::copy(objects.begin(), objects.end(), std::ostream_iterator<Object>(std::cout, ", ")); std::cout << std::endl; std::for_each(objects.begin(), objects.end(), Functor(1)); std::cout << "for_each Functor" << std::endl; std::copy(objects.begin(), objects.end(), std::ostream_iterator<Object>(std::cout, ", ")); std::cout << std::endl; std::for_each(objects.begin(), objects.end(), function_modify); std::cout << "for_each function" << std::endl; std::copy(objects.begin(), objects.end(), std::ostream_iterator<Object>(std::cout, ", ")); std::cout << std::endl; std::for_each(objects.begin(), objects.end(), [](Object& object) { object.modify = 3; } ); std::cout << "for_each lambda" << std::endl; std::copy(objects.begin(), objects.end(), std::ostream_iterator<Object>(std::cout, ", ")); std::cout << std::endl; for (auto& object: objects) { object.modify = 4; } std::cout << "for" << std::endl; std::copy(objects.begin(), objects.end(), std::ostream_iterator<Object>(std::cout, ", ")); std::cout << std::endl; return 0; }
Standard input is empty
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,