Re:Clever code is probably the worst code you could write
by MathMonkeyMan on Tuesday May 21, 2024 @08:24PM
(#40435971)
Just make sure you're accumulating integers and not doubles!
Re:Clever code is probably the worst code you could write
by a_t48 on Wednesday May 22, 2024 @12:41AM
(#40437411)
Obviously, you have to use
std::accumulate(v.cbegin(), v.cend(), decltype(*v.cbegin()){});
:) :) :)
Re:Clever code is probably the worst code you could write
by floxy on Thursday May 23, 2024 @12:52AM
(#40450601)
#include<cstdio>
#include<numeric>
#include<vector>
using namespace std;
template <class T, template<class> class Cont>
T sum(Cont<T> x)
{
return accumulate(x.begin(), x.end(), (T)0);
}
int main(int argc, char *argv[])
{
vector<double> ds({1.1, 2.2, 3.3, 4.4});
vector<float> fs({1.1f, 2.2f, 3.3f, 4.4f});
vector<int> is({1, 2, 3, 4});
vector<unsigned long long> ulls({1ul, 2ul, 3ul, 4ul});
printf("doubles: %f\n",sum(ds));
printf("floats: %f\n",sum(fs));
printf("ints: %d\n",sum(is));
printf("ulls: %llu\n",sum(ulls));
return 0;
}
Accumulate, surprisingly enough, accumulates by default: