我正在使用现有的C ++代码库,但在调用函数时遇到麻烦。
[我正在尝试使用代码库中已有的较早的Eigen库的线性回归函数,您可以看到that source code here,但下面是相关的声明。
template<typename VectorType>
void linearRegression(int numPoints,
VectorType **points,
VectorType *result,
int funcOfOthers )
{ ... }
下面是我的代码的匿名副本:
// MyClass has member variable int maxIdx = 5
void MyClass::myFunction()
{
Eigen::Vector2d points[maxIdx];
Eigen::Vector2d coeffs;
for(int i = 0; i < maxIdx; i++)
{
points[i] = Eigen::Vector2d(data->mydata[i].x, data->mydata[i].y);
}
Eigen::linearRegression( maxIdx, &points, &coeffs, 1 );
// do more stuff with coeffs
}
这是我尝试编译时收到的错误消息:
myfile.cpp:803:67: error: no matching function for call to 'linearRegression(int, Eigen::Vector2d (*)[((MyClass*)this)->MyClass::maxIdx], Eigen::Vector2d*, int)'
Eigen::linearRegression( maxIdx, &points, &coeffs, 1 );
^
myfile.cpp:803:67: note: candidate is:
In file included from [redacted]:
lib/Eigen/src/Eigen2Support/LeastSquares.h:85:6: note: template<class VectorType> void Eigen::linearRegression(int, VectorType**, VectorType*, int)
void linearRegression(int numPoints,
^
lib/Eigen/src/Eigen2Support/LeastSquares.h:85:6: note: template argument deduction/substitution failed:
myfile.cpp:803:67: note: mismatched types 'VectorType*' and 'Eigen::Vector2d [((MyClass*)this)->MyClass::maxIdx] {aka Eigen::Matrix<double, 2, 1> [((MyClass*)this)->MyClass::maxIdx]}'
这几乎是库源代码中示例代码的精确副本,因此我对如何解决此问题有些困惑。我对模板不是很熟悉,所以类型错误可能与此有关?
根据that来源(与示例中的内容不同),points
应该是指向这些点的指针数组。也就是说,
Eigen::Vector2d *points[maxIdx];
所以,
Eigen::Vector2d points[maxIdx];
Eigen::Vector2d *point_ptrs[maxIdx];
for(int i = 0; i < maxIdx; i++)
point_ptrs[i] = &points[i];
...
Eigen::linearRegression(maxIdx, point_ptrs, &coeffs, 1);
Vector2d
看起来很愚蠢,但可能是为无法复制的巨大矢量设计的。
为了补充@numzero的答案,该代码已编译,但是当我尝试执行它时遇到运行时崩溃。看起来第二个参数需要指向该指针数组中的first index。 This answer解释了正在发生的事情,即使它在运行时也失败了。
这是最终为我工作的东西:
Eigen::Vector2d points[maxIdx];
std::vector<Eigen::Vector2d*> point_ptrs(maxIdx);
Eigen::Vector2d coeffs;
for(int i = 0; i < maxIdx; i++)
{
points[i] = Eigen::Vector2d(data->mydata[i].x, data->mydata[i].y);
point_ptrs[i] = &points[i];
}
Eigen::linearRegression( maxIdx, &(point_ptrs[0]), &coeffs, 1 );