1

我有以下课程。当我通过方法 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*)’
4

1 回答 1

3

你的问题是 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();
于 2013-07-29T18:39:38.393 回答