(C++) Answer of exercise \#9: No for-loops \#24
January 10, 2018 · View on GitHub
This is the answer of Exercise #9: No for-loops.
Question #24: SumSecond
Replace the for-loop. You will need:
int SumSecond(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].second; } 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 SumSecond(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>::second, _2) ) ); }
Answer using Boost.Lambda
Thanks to 'ofwolfandman':