(C++) Answer of exercise \#9: No for-loops \#19
January 11, 2018 · View on GitHub
(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:
- std::bind2nd.htm
- std::greater.htm
- std::multiplies.htm
- A conditional std::accumulate
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)); }