是否有一个 STL 算法采用谓词来总结 C++ 中向量的元素

Is there an STL algo that takes predicate for summing up the elements of a vector in C++

我一直在做一项作业来理解 C++ 库中给出的所有 STL 算法,我们应该避免使用 for_each 和 for 循环来解决问题。在大多数情况下,我能够找到适用的 STL 算法,但我不记得任何在使用谓词时对集合或范围求和的算法,而且我在论坛上也找不到解决方案。我正在使用 C++ 20。

唯一的objective是用STL算法将向量中的偶数求和到一个变量。

我会用std::accumulate.

示例:

#include <iostream>
#include <numeric>
#include <vector>

int main() {   
    std::vector<int> v{1,2,3,4,5};
    auto result = std::accumulate(v.begin(), v.end(), 0,
        [](auto x, auto y) {
            return y%2==0 ? x+y : x; 
        });
    std::cout << result << '\n';  // prints 6
}