this is an exercise from a previous c++ test I took:
Implement a template function sum which takes in a numbers container and returns their sum. (Tip: if C it's the container type, the elements type is returned, for example, from C::value_type).
At the time of the test I wasn't prepared at all, but now, for a sum of a generic container I'd go like that:
template<typename Iter>
double sum(Iter b, Iter e)
{
double ret=0;
for(;b!=e;b++)
ret+=*b;
return ret;
}
or
template<typename C>
double sum(const C& cnt)
{
double ret=0;
for(auto it=cnt.begin();it!=cnt.end();it++)
ret+=*it;
return ret;
}
My question here is how can I replace the function return argument with the actual container elements type?
Aucun commentaire:
Enregistrer un commentaire