Is there a “accummulate_if”?

后端 未结 3 1157
执念已碎
执念已碎 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:05

    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
    

提交回复
热议问题