在自定义对象中使用accumulate

Usage of accumulate with a custom object

本文关键字:accumulate 自定义 对象      更新时间:2023-10-16

我正在使用c++的opencv库,我正试图计算vector<Point2f> difference

中包含的点的总和

Point类的x属性是float

float pointSumX(Point2f pt1,Point2f pt2)
{
    return (pt1.x + pt2.x);
}

我如上所述定义了函数,并从如下所示的accumulate调用它。但是会抛出错误

float avgMotionX = accumulate(difference.begin(),difference.end(),0,pointSumX);

错误是:

错误:无法将' __init '从' int '转换为' cv::Point_ ' __init = __binary_op(__init, *__first);

注意:我使用c++ 11

float pointSumX(Point2f pt1, Point2f pt2)
应该

float pointSumX(float lhs, const Point2f& rhs)
{
    return lhs + rhs.x;
}

作为lhs为累加器。

还要注意,你应该把它叫做

std::accumulate(difference.begin(), difference.end(), 0.f, pointSumX); // 0.f instead of 0

返回float而不是int