This is the answer of Exercise #9: No for-loops.
Question #23: SumFirst
Replace the for-loop. You will need:
int SumFirst(const std::vector<std::pair<int,int> >& v) { const int size = static_cast<int>(v.size()); int sum = 0; for (int i=0; i!=size; ++i) { sum+=v[i].first; } return sum; }
Answer using STL only
You may contact me if you have an STL solution...
Answer using Boost.Bind
Thanks to 'ofwolfandman':
#include <functional> #include <numeric> #include <utility> #include <vector> #include <boost/bind.hpp> int SumFirst(const std::vector<std::pair<int,int> >& v) { return std::accumulate( v.begin(), v.end(), static_cast<int>(0), boost::bind( std::plus<int>(), _1, boost::bind<int>(&std::pair<int,int>::first, _2) ) ); }
Answer using Boost.Lambda
Thanks to 'ofwolfandman':