Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

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

 

 

 

 

 

 

Question #32: Sum all persons' money from a std::vector<const Person*>

 

Replace the for-loop. You will need:

 

#include <vector>

struct Person
{
  Person(const int money) : m_money(money) {}
  int GetMoney() const { return m_money; }
  private:
  int m_money;
};

int SumMoney(const std::vector<const Person*>& v)
{
  int sum = 0;
  const int sz = v.size();
  for (int i=0; i!=sz; ++i)
  {
    sum+=v[i]->GetMoney();
  }
  return sum;
}

 

 

 

 

 

C++98Boost Answer using Boost.Bind

 

#include <functional>
#include <numeric>
#include <vector>
#include <boost/bind.hpp>
#include <boost/lambda/bind.hpp>

struct Person
{
  Person(const int money) : m_money(money) {}
  int GetMoney() const { return m_money; }
  private:
  int m_money;
};

int SumMoney(const std::vector<const Person*>& v)
{
  return std::accumulate(
    v.begin(),
    v.end(),
    static_cast<int>(0),
      boost::bind(std::plus<int>(),_1,
        boost::bind(&Person::GetMoney,boost::lambda::_2)));
}

 

 

 

 

 

C++11STL Answer using the C++11 STL

 

#include <numeric>
#include <vector>

struct Person
{
  Person(const int money) : m_money(money) {}
  int GetMoney() const { return m_money; }
  private:
  int m_money;
};

int SumMoney(const std::vector<const Person*>& v)
{
  return std::accumulate(
    v.begin(),v.end(),0,
    [](int& sum,const Person* p)
    {
      return sum + p->GetMoney();
    }
  );
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict