在类成员函数中累积同一类的对象

Accumulate objects of the same class within a class member function

本文关键字:一类 对象 函数 成员      更新时间:2023-10-16

我有以下类。当我用方法1(注释)计算_avg_lifetime时,它会编译,但它不会用方法2用std:cumulate编译。为什么?

#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();