繁体   English   中英

是否有一个 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。

唯一的目标是使用 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM