Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

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

 

This is the answer of Exercise #9: No for-loops.

 

 

 

 

 

Question

 

Replace the for-loop. You will need:

 

int ProductNonZeroPositives(const std::vector<int>& v)
{
  const size_t sz = v.size();
  int product = 0;
  for (size_t i=0; i!=sz; ++i)
  {
    if (v[i]>0) product*=v[i];
  }
  return product;
}

 

 

 

 

 

Answer

 

//From http://www.richelbilderbeek.nl/CppAccumulate_if.htm
template
  <
  typename InputIterator,
  typename ElementType,
  typename BinaryOperation,
  typename Predicate
  >
const ElementType std::accumulate_if(
  InputIterator first,
  const InputIterator last,
  ElementType init,
  const BinaryOperation binary_op,
  const Predicate predicate)
{
  for (; first != last; ++first)
    if (predicate(*first)) init = binary_op(init, *first);
  return init;
}

#include <vector>

//From http://www.richelbilderbeek.nl/CppProductNonZeroPositives.htm
int ProductNonZeroPositives(const std::vector<int>& v)
{
  return ::std::accumulate_if(
    v.begin(),
    v.end(),
    1,
    std::multiplies<int>(),
    std::bind2nd(std::greater<int>(),0));
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict