简体   繁体   English

在std :: accumulate C ++中使用模板Lambda表达式?

[英]Using a template Lambda expression inside a std::accumulate c++?

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.? 如果存在标准容器double或float等,是否可以在下面的lambda函数中对“ int”进行模板化? 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. 提前致谢。

There is typically a way to get the type of the contained data from a container. 通常有一种方法可以从容器中获取所包含数据的类型。

For eg you could replace the int s in that function with T::value_type which should support all containers which expose such a typedef. 例如,您可以用T::value_type替换该函数中的int ,它应支持所有公开此类typedef的容器。

This wont work for types such as map but you can specialize for it if you want to support them. 这不适用于map等类型,但是如果您要支持它们,可以对其进行专业化处理。

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 将始终返回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); 这里的答案>>> 使用std :: accumulate的计算平均值在Edit部分中失败 ,这并不是真的正确,就好像我更改了vf.push_back(1.3); into vf.push_back(3.3); 进入vf.push_back(3.3); I'll obtain the wished result. 我会得到理想的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM