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; }
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))); }
#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(); } ); }
height="32"}](http://validator.w3.org/check?uri=referer)