Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "accummulate_if"?

Tags:

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 accummulate_if but there isn't any. Thanks!

update: Thanks for all the kind answers. I end up doing it this way:

std::for_each(v.begin(), v.end(), [&](int x){if (Pred) sum += x;});

like image 972
JASON Avatar asked Nov 17 '13 08:11

JASON


1 Answers

Must you really use an algorithm? Something as simple as below 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;}  );    
like image 73
Leonid Volnitsky Avatar answered Oct 04 '22 01:10

Leonid Volnitsky