Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

 

 

 

 

C++98STL 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));
}

 

 

 

 

 

C++98Boost 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));
}

 

 

 

 

 

C++11STL 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(); } );
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict