首页 > 解决方案 > 是否有一个 STL 算法采用谓词来总结 C++ 中向量的元素

问题描述

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

唯一的目标是使用 STL 算法将向量中的偶数与变量相加。

标签: c++vectorstlc++17c++20

解决方案


我会用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
}

推荐阅读