문제

I'm trying to create a class that calculates its variance from a vector<float>. It should do this by using its previously calculated this->mean in diffSquaredSum. I'm trying to call the method diffSquaredSum inside of accumulate but have no idea what the magical syntax is.

What is the correct syntax to use the diffSquaredSum class method as the op argument to accumulate in setVariance?

float diffSquaredSum(float sum, float f) {
    // requires call to setMean
    float diff = f - this->mean;
    float diff_square = pow(diff,2);
    return sum + diff_square;
}

void setVariance(vector<float>& values) {
    size_t n = values.size();
    double sum = accumulate(
        values.begin(), values.end(), 0, 
        bind(this::diffSquaredSum));
    this->variance = sum / n;
}
도움이 되었습니까?

해결책

double sum = std::accumulate(
  values.begin(),
  values.end(),
  0.f,
  [&](float sum, float x){ return diffSquaredSum(sum,x);}
);

bind is only rarely useful. Prefer lambdas, they are easier to write and read.

You could instead get fancy with binding, but why?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top