【问题标题】:std::inner_product to calculate the standard deviation of a vectorstd::inner_product 计算向量的标准差
【发布时间】: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&lt;std::vector&lt;float,std::allocator&lt;float&gt;&gt;,std::allocator&lt;std::vector&lt;float ,std::allocator&lt;float&gt;&gt;&gt;&gt; &amp;)" : Konvertierung von Argument 1 von "std::vector&lt;float,std::allocator&lt;float&gt;&gt;" in "std::vector&lt;std::vector&lt;float,std::allocator&lt;float&gt;&gt;,std::allocator&lt;std::vector&lt;float,std ::allocator&lt;float&gt;&gt;&gt;&gt; &amp;" nicht möglich
  • 问题出在呼叫现场。我们需要调用这个函数的代码和传递给它的变量的定义。
  • @shyney 初始值 0.0 的类型为 double。将其更改为 0.0f。
  • @VladfromMoscow 如果你的意思是累加器的初始值,我在两次调用中都将其更改为 0.0f,我得到了同样的错误。

标签: c++ algorithm compiler-errors numeric cmath


【解决方案1】:

错误信息表示参数的类型是std::vector&lt;float&gt;

std::vector<float> testv {6,3,2,9,11,44,20};
float stdw = stdfunc(testv);

std::vector&lt;std::vector&lt;float&gt;&gt; 的函数参数类型不对应。

所以检查函数声明。不排除函数声明和函数定义可以不同。

【讨论】:

  • 您是否还知道如何迭代 2D 向量的每一列,以使用与 1D 向量相同的方法使用 inner_product 计算标准差?
  • @shyney 您可以在函数中使用基于范围的 for 循环用于外部向量,然后为内部向量应用您的算法
猜你喜欢
  • 2019-02-09
  • 1970-01-01
  • 2016-04-14
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
  • 2020-08-13
  • 2019-08-15
相关资源
最近更新 更多