【发布时间】:2020-03-31 18:46:52
【问题描述】:
我正在尝试创建一个函数来计算标准偏差。
我尝试对 inner_product 的 op1 和 op2 使用 std::inner_product 和 lambda 表达式来修改 std::inner_product 函数的操作。
不幸的是,在主循环中调用函数时出现编译器错误:
error C2664: cannot convert parameter 1 from "std::vector<float,std::allocator<float>>" in "std::vector<std::vector<float,std::allocator<float>>,std::allocator<std::vector<float,std::allocator<float>>>> &"
这是我的代码:
#include <numeric>
#include <cmath>
float stdfunc(std::vector<float> const & invector) {
float mean = std::accumulate(invector.begin(), invector.end(), 0.0) / invector.size();
float sq_sum = std::inner_product(invector.begin(), invector.end(), invector.begin(), 0.0,
[](float const & x, float const & y) {return x+y;},
[mean](float const & x, float const & y) {return (x-mean)*(y-mean);});
return std::sqrt(sq_sum / (invector.size() - 1));
}
调用main:
int main(){
std::vector<float> testv {6,3,2,9,11,44,20};
float stdw = stdfunc(testv);
std::cout << "Standardabw: " << stdw << std::endl;
return 0;
}
我希望你能帮助我。
【问题讨论】:
-
显示完整的错误信息。
-
@VladfromMoscow 不幸的是,我的编译器以我的母语显示消息,如果你愿意,我可以翻译它:
error C2664: "float stdfunc(std::vector<std::vector<float,std::allocator<float>>,std::allocator<std::vector<float ,std::allocator<float>>>> &)" : Konvertierung von Argument 1 von "std::vector<float,std::allocator<float>>" in "std::vector<std::vector<float,std::allocator<float>>,std::allocator<std::vector<float,std ::allocator<float>>>> &" nicht möglich -
问题出在呼叫现场。我们需要调用这个函数的代码和传递给它的变量的定义。
-
@shyney 初始值 0.0 的类型为 double。将其更改为 0.0f。
-
@VladfromMoscow 如果你的意思是累加器的初始值,我在两次调用中都将其更改为 0.0f,我得到了同样的错误。
标签: c++ algorithm compiler-errors numeric cmath