我有以下课程。当我通过方法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*)’
答案 0 :(得分: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();