Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Answer of exercise #9: No for-loops #6

 

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));
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict