(C++) Answer of exercise \#9: No for-loops \#4
January 11, 2018 · View on GitHub
(C++) Answer of exercise #9: No for-loops #4
This is the answer of Exercise #9: No for-loops.
Question #4: Widget::DoIt on Widget
Replace the for-loop. You will need std::for_each and std::mem_fun_ref.
#include <vector> struct Widget { void DoIt() const { /* do it */ } }; void DoIt(const std::vector<Widget>& v) { const int sz = static_cast<int>(v.size()); for (int i=0; i!=sz; ++i) { v[i].DoIt(); } }

Answer using C++98 its STL
#include <algorithm> #include <functional> #include <numeric> #include <vector> struct Widget { void DoIt() const { /* do it */ } }; void DoIt(const std::vector<Widget>& v) { std::for_each(v.begin(),v.end(),std::mem_fun_ref(&Widget::DoIt)); }

Answer using C++98 and Boost
#include <algorithm> #include <vector> #include <boost/mem_fn.hpp> struct Widget { void DoIt() const { /* do it */ } }; void DoIt(const std::vector<Widget>& v) { std::for_each(v.begin(),v.end(),boost::mem_fn(&Widget::DoIt)); }

Answer using C++11 its STL
Instead of using a functor, use a lambda expressions.
#include <algorithm> #include <vector> void DoIt(const std::vector<Widget>& v) { std::for_each(v.begin(),v.end(),[](const Widget& w) { w.DoIt(); } ); }