I need to apply a custom func
to an STL containers by pairs -> that is:
// if c => {a,b,c,d,e,f,g}; // a,b,c,.. are just aliases for some object
my_algorithm(c.begin(),c.end(),[](auto a, auto b){ a + b }); // c++14
should resolve into something like this:
temp1 = a + b;
temp2 = c + d;
temp3 = e + f;
temp4 = temp1 + temp2;
temp5 = temp3 + g;
result = temp4 + temp5;
(I am sure this kind of algorithm has a proper name but I have no idea what this may be)
I have tried with std::accumulate
, I am not sure if its implementation is defined by the standard, but in my case and with my compiler it seems to resolve to this (I think this is called pairwise summation, right?) :
temp1 = a + b;
temp2 = temp1 + c;
temp3 = temp2 + d;
// etc
which is more less the same I can get with
auto temp = c[0];
std::for_each(c.begin()+1,c.end(),[&temp](auto a){temp + a); // c++14
I browsed STL and Boost, but did not manage to find something relevant. Is there any library that provides such an algorithm? If not, any ideas for a good STL compliant implementation?
EDIT Just to add that I'm not really interested in adding the elements in the traditional sense - in that case order does not really matter. My function will do a more complex, weighted, kind of summation and will give different results if carried out this way. My question is more generic nevertheless.
std::accumulate
is definitely defined by the standard to do a left fold. It seems that you want to bottom-up construct a balanced tree, which is possible but not in the standard library afaik. ("Construct a balanced tree" has different algorithms, depending on your definition of "balanced", which you only provide by a single example; I don't think that's precise enough for an implementation.) – Marginalfunc(a,b)
may be different thanfunc(temp3, g)
, and it keeps all the temporaries in memory the whole time... – Atmospherics