Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) accumulate_if

 

Algorithm similar to std::accumulate, except that accumulate_if also needs a predicate argument.

 

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

 

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

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict