Question

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;
}
Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top