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.

4

2 回答 2

1

通常有一种方法可以从容器中获取所包含数据的类型。

例如,您可以替换该函数中的ints,该函数T::value_type应该支持所有公开此类 typedef 的容器。

这不适用于诸如此类的类型,map但如果您想支持它们,您可以专门针对它。

于 2013-01-12T03:23:45.920 回答
-1

但在我看来,以这种方式编写这样的函数可能会导致数据丢失,例如

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);

将始终返回 1

这里的答案 >>>使用 std::accumulate 计算均值在编辑部分失败并不是真的,就好像我vf.push_back(1.3);改成vf.push_back(3.3);我会得到想要的结果一样。

于 2013-01-12T03:41:26.627 回答