Search code examples
c++c++11stlstl-algorithm

Using function object in stl algorithm


When trying to use a conditional copy_if algorithm to copy only the values that are lower than mean of values in a vector into another vector, I hit a snag with my function object:

struct Lower_than_mean
{
private:
    double mean;
    vector<double>d1;
public:
    Lower_than_mean(vector<double>a)
        :d1{a}
    {
        double sum = accumulate(d1.begin(), d1.end(), 0.0);
        mean = sum / (d1.size());
    }
    bool operator()(double& x)
    {
        return x < mean;
    }

};

int main()
{
    vector<double>vd{ 3.4,5.6, 7, 3,4,5.6,9,2 };
    vector<double>vd2(vd.size());

    copy_if(vd.begin(), vd.end(), vd2, Lower_than_mean(vd));

}

What is the right way of going about this?


Solution

  • You used vd instead of vd.begin() in the call to std::copy_if.

    But, seriously, you didn't bother to even read your compiler output...

    Also, like @zch suggests - your approach doesn't make sense: Don't keep re-calculating the mean again and again. Instead, calculate it once, and then your function becomes as simple [mean](double x) { return x < mean; } lambda.