Bhoke Bhoke - 1 year ago 117
C++ Question

Usage of accumulate with a custom object

I am using opencv library with C++, and I am trying to compute sum of points which are contained in

vector<Point2f> difference

Point class has x property which is

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

I defined function as above, and call it from accumulate shown below. But it throws error.

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

Error is:

error: could not convert ‘__init’ from ‘int’ to ‘cv::Point_’ __init = __binary_op(__init, *__first);

Note: I am using C++11

Answer Source
float pointSumX(Point2f pt1, Point2f pt2)

should be

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

as lhs is the accumulator.

Note also that you should call it

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

to return float and not int.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download