Help with std::accumulate
Nov 3, 2018 at 5:38pm UTC
Hello friends, I'm wanting to translate the following code using td::accumulate, but I'm still confused with the syntax. Here is he code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
unsigned int binomial(int n, int k) {
std::vector<unsigned int > S(k + 1, 0u);
S[0] = 1u;
for (int i = 1; i <= n; i++) {
for (int j = std::min(i, k); j > 0; j--)
S[j] = S[j] + S[j - 1];
}
return S[k];
}
unsigned int rank(const std::vector<int > &S) {
unsigned int r = 0u;
int k = 1;
for (auto n = S.begin(); n != S.end(); n++, k++){
r += binomial(*n, k);
}
return r;
}
How would be the rank function translated to std::accumulate?
1 2 3 4
return std::accumulate(S.begin(), S.end(), 0u, [&] // ?(int n) {
// ?? return binomial(n, k++);
});
Nov 3, 2018 at 7:15pm UTC
http://www.cplusplus.com/reference/numeric/accumulate/
States:
Binary operation taking an element of type T as first argument and an element in the range as second, and which returns a value that can be assigned to type T.
and
init = init + *first; // or: init=binary_op(init,*first) for the binary_op version
Does that mean:
1 2 3 4
[&k] (unsigned int init, int elem)
{
return init + binomial(elem, k++);
}
Nov 3, 2018 at 8:01pm UTC
Absolutely perfect my friend. Thank you!
Topic archived. No new replies allowed.