0

Is there to templatize the "ints" in the lambda function below in the case that there was a standard container of doubles or floats, etc.? I have searched the world over for help with this. I even asked for the help of my professor who says it is possible but is to cryptic about the answer.

template <typename T>
   float mean(T &container)
   {
     auto sum = std::accumulate(container.begin(), container.end(), 0/*initial value*/,
     [](int total, int cur)
     {
          return total+cur;
     }//end of lambda
   );//end of accumulate
   return static_cast<float>(sum) / container.size(); //to find the mean
}//end of mean

Thanks in advance.

OakleyMaster
  • 41
  • 1
  • 3

2 Answers2

1

There is typically a way to get the type of the contained data from a container.

For e.g you could replace the ints in that function with T::value_type which should support all containers which expose such a typedef.

This wont work for types such as map but you can specialize for it if you want to support them.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • Thanks! I have figured a way around it that works okay. It just forces the function call to look something like this. float initialValue = 0.0; mean(container, initialValue); Then I added an extra template value to catch the data type of initialValue. – OakleyMaster Jan 12 '13 at 18:44
-1

But it seems to me that writing such a function that way may induce loss of data For example

std::vector<float> vf;
vf.push_back(1.3);
vf.push_back(1.5);
vf.push_back(1.3);
vf.push_back(1.123);
vf.push_back(1.526);
float m=mean(vf);

will always return 1

The answer here >>> compute mean using std::accumulate fails in the Edit part is not really true as if I change vf.push_back(1.3); into vf.push_back(3.3); I'll obtain the wished result.

Community
  • 1
  • 1