Is there a “accummulate_if”?

后端 未结 3 1164
执念已碎
执念已碎 2020-12-31 02:47

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

3条回答
  •  一个人的身影
    2020-12-31 03:31

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

提交回复
热议问题