Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

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

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict