簡體   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