Is there a function similar to accummulate() but provides a unary pre-condition to filter the linear container when performing the operation? I search for
No, but you can write it yourself:
template
<
typename InputIterator,
typename AccumulateType,
typename BinaryOperation,
typename Predicate
>
const AccumulateType accumulate_if(
InputIterator first,
const InputIterator last,
AccumulateType init,
BinaryOperation&& binary_op,
Predicate&& predicate)
{
for (; first != last; ++first)
if (predicate(*first)) init = binary_op(init, *first);
return init;
}
Usage:
int main(int argc, char* argv[])
{
std::vector v = {1,2,3,4,5};
std::cout << accumulate_if(v.begin(), v.end(), 0, std::plus(), [] (int n) { return n > 3; });
return 0;
} // outputs 9