Skip to content

Latest commit

 

History

History
39 lines (23 loc) · 3.65 KB

CppExerciseNoForLoopsAnswer23.md

File metadata and controls

39 lines (23 loc) · 3.65 KB

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

STL Answer using STL only

You may contact me if you have an STL solution...

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

Boost Answer using Boost.Lambda

Thanks to 'ofwolfandman':


#include <functional> #include <numeric> #include <utility> #include <vector> #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> int SumFirst(const std::vector<std::pair<int,int> >& v) {   return std::accumulate(     v.begin(),     v.end(),     static_cast<int>(0),     boost::lambda::_1     + boost::lambda::bind(       &std::pair<int, int>::first, boost::lambda::_2       )   ); }