Skip to content

Latest commit

 

History

History
114 lines (66 loc) · 4.35 KB

CppExerciseNoForLoopsAnswer5.md

File metadata and controls

114 lines (66 loc) · 4.35 KB

 

 

 

 

 

 

This is the answer of Exercise #9: No for-loops.

 

 

 

 

 

Question #5: Widget::DoItOften on Widget

 

Replace the for-loop. You will need:

 


#include <vector>   struct Widget {   void DoItOften(const int n) const { /* do it n times */ } };   void DoItOften(const std::vector<Widget>& v, const int n) {   const int sz = v.size();   for (int i=0; i!=sz; ++i)   {     v[i].DoItOften(n);   } }

 

 

 

 

 

STL Answer using STL only

 


#include <algorithm> #include <numeric> #include <vector> struct Widget {   void DoItOften(const int n) const { /* do it n times */ } }; void DoItOften(const std::vector<Widget>& v, const int n) {   std::for_each(     v.begin(),     v.end(),     std::bind2nd(std::mem_fun_ref(&Widget::DoItOften),n)); }

 

 

 

 

 

Boost Answer using Boost

 


#include <algorithm> #include <vector> #include <boost/bind.hpp> struct Widget {   void DoItOften(const int n) const { /* do it n times */ } }; void DoItOften(const std::vector<Widget>& v, const int n) {   std::for_each(     v.begin(),     v.end(),     boost::bind(&Widget::DoItOften, _1, n)); }

 

Note that you do not need boost::mem_fn, because it is added for you. If this is done by hand, like in the code below, the solution is still correct.

 


void DoItOften(const std::vector<Widget>& v, const int n) {   std::for_each(     v.begin(),     v.end(),     boost::bind(boost::mem_fn(&Widget::DoItOften), _1, n)); }

 

Note that _1 is a placeholder of type boost::arg<1> and can be found in boost/bind/placeholders.hpp.