Skip to content

Latest commit

 

History

History
87 lines (49 loc) · 2.81 KB

CppExerciseNoForLoopsAnswer6.md

File metadata and controls

87 lines (49 loc) · 2.81 KB

 

 

 

 

 

 

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

 

Question #6: Widget::DoIt on Widget*

 

Replace the for-loop. You will need:

 


#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 STL-only

 


#include <algorithm> #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(&Widget::DoIt)); }

 

 

 

 

 

Answer using Boost

 


#include <algorithm> #include <boost/mem_fn.hpp> #include <vector> 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)); }