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<int> v = {1,2,3,4,5};
std::cout << accumulate_if(v.begin(), v.end(), 0, std::plus<int>(), [] (int n) { return n > 3; });
return 0;
} // outputs 9
Pass your own binary op to std::accumulate():
#include <iostream>
#include <vector>
#include <numeric>
bool meets_criteria(int value) {
return value >= 5;
}
int my_conditional_binary_op(int a, int b) {
return meets_criteria(b) ? a + b : a;
}
class my_function_object {
private:
int threshold;
public:
my_function_object(int threshold) :
threshold(threshold) {
}
bool meets_criteria(int value) const {
return value >= threshold;
}
int operator()(int a, int b) const {
return meets_criteria(b) ? a + b : a;
}
};
int main() {
std::vector<int> v { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//sum [5...10] = 45
int sum;
sum = std::accumulate(v.begin(), v.end(), 0, my_conditional_binary_op);
std::cout << sum << std::endl;
//Use a function object to maintain states and additional parameters like 'threshold'
sum = std::accumulate(v.begin(), v.end(), 0, my_function_object(5));
std::cout << sum << std::endl;
return sum;
}
Do you really must to use an algorithm? Something as simple as bellow won't do?
for (const auto& v: V) if(pred(v)) sum+=v;
Sam's idea is also good. But I would do it with lambda:
sum = accumulate(
V.begin(), V.end(), 0,
[](int a, int b){return pred(b)? a+b: a;}
);