我有以下类(class)。当我通过方法1计算_avg_lifespan时(有注释),它会编译,但是不会使用std:accumulate的方法2进行编译。为什么?

#include <vector>
#include <numeric>
#include <stdlib.h>
#include <functional>
#include <iostream>
using namespace std;

class Raven{
    public:
        Raven()
        {
            _lifespan = rand() % 15;
        }
        int sum_life(int sum, Raven *rhs)
        {
            return sum + rhs->get_lifespan();
        }
        void set_avg_lifespan(vector<Raven*> flock)
        {
            //Method 1 works :-)
            /*
            int sum = 0;
            vector<Raven*>::iterator it = flock.begin();
            while( it < flock.end() )
            {
                sum += (*it++)->get_lifespan();
                cout << sum << endl;
            }
            _avg_lifespan = (float)sum/flock.size();
            */
            //Method 2 does not work :-(
            _avg_lifespan = (float)std::accumulate(flock.begin(), flock.end(),0,sum_life)/flock.size();
        }
        int get_lifespan( ) { return _lifespan; }
        float get_avg_lifespan( ) { return _avg_lifespan; }
    private:
        int _lifespan;
        float _avg_lifespan;
};

错误是:
argument of type ‘int (Raven::)(int, Raven*)’ does not
match ‘int (Raven::*)(int, Raven*)’

最佳答案

您的问题是Raven::sum_life是成员函数。
幸运的是,您可以使用std::bind并将“this”作为第一个参数传递。
您的代码如下所示:

auto f = std::bind(&Raven::sum_life, this, std::placeholders::_1, std::placeholders::_2);
_avg_lifespan = (float)std::accumulate(flock.begin(), flock.end(),0,f)/flock.size();

关于c++ - 在类成员函数中累积相同类的对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17931317/

10-11 15:36