将accumulate 与自定义对象一起使用

Bho*_*oke 3 c++ opencv c++11

我正在使用带有 C++ 的 opencv 库,并且我正在尝试计算包含在中的点的总和vector<Point2f> difference

\n\n

点类具有 x 属性,即float

\n\n
float pointSumX(Point2f pt1,Point2f pt2)\n{\n    return (pt1.x + pt2.x);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我如上定义了函数,并从如下所示的accumulate 中调用它。但它会引发错误。

\n\n
float avgMotionX = accumulate(difference.begin(),difference.end(),0,pointSumX);\n
Run Code Online (Sandbox Code Playgroud)\n\n

错误是:

\n\n
\n

错误:无法将 \xe2\x80\x98__init\xe2\x80\x99 从 \xe2\x80\x98int\xe2\x80\x99 转换为 \xe2\x80\x98cv::Point_\xe2\x80\x99 __init = __binary_op( __init, *__first);

\n
\n\n

注意:我使用的是C++11

\n

Jar*_*d42 8

float pointSumX(Point2f pt1, Point2f pt2)
Run Code Online (Sandbox Code Playgroud)

应该

float pointSumX(float lhs, const Point2f& rhs)
{
    return lhs + rhs.x;
}
Run Code Online (Sandbox Code Playgroud)

lhs累加器也是如此。

另请注意,您应该调用它

std::accumulate(difference.begin(), difference.end(), 0.f, pointSumX); // 0.f instead of 0
Run Code Online (Sandbox Code Playgroud)

float而不归int

  • @Bhoke:为了避免复制:通过 const 引用而不是值传递。(对于“Point2f”,它可能是有争议的,因为类很小,但默认情况下通过 const 引用而不是通过值传递对象)。 (2认同)