Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

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

 

 

 

 

 

Question #7: 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(&Widget::DoItOften),n));
}

 

 

 

 

 

Boost Answer using Boost

 

#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(),
    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.

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict