Talk:cpp/algorithm/accumulate
[edit] Suggestion
This is the same as a high level fold. It might be good to mention this.
Zzing 23:57, 16 January 2012 (PST)
134.130.190.58 04:35, 29 February 2016 (PST)gb I never remember if the accumulated parameter is passed as the first or second argument to the binary operator and this page doesnt really help much clarifying it.
It might be worth it to rename `a` and `b` in the signature of the binaryoperator to `acc` and `i`, and explain that `acc` is the last acummulated value (initialized to the initial value) and `i` the value of the current element.
[edit] Order of Arguments
When I build an example based on the dashfold lambda here I found that it did not compile on GCC 10. The order of arguments is reversed. Can anyone explain the difference? Is the example incorrect? See example here.
Jac18281828 (talk) 08:59, 14 May 2021 (PDT)
Your example online. |
---|
Run this code #include <iostream> #include <vector> #include <numeric> namespace { struct bird { int type; }; inline int birdbrain(bird const& b) { if(b.type == 1) { return 5; } else if(b.type == 2) { return 10; } return 0; // <-- or anything else :) } } int main(/*int argc, char* argv[]*/) { std::vector<bird> intvec; intvec.push_back({1}); intvec.push_back({2}); intvec.push_back({2}); auto summer = [](int sum, auto const& b1) -> int { return birdbrain(b1) + sum; }; std::cout << "Sum " << std::accumulate(std::begin(intvec), std::end(intvec), 0, summer) << std::endl; return 0; } Output: Sum 25 |