C++ 在类成员函数中累积同一类的对象
我上过下面的课。当我使用方法1(注释)计算_avg_寿命时,它会编译,但是它不会使用std:acculate使用方法2编译。为什么?C++ 在类成员函数中累积同一类的对象,c++,C++,我上过下面的课。当我使用方法1(注释)计算_avg_寿命时,它会编译,但是它不会使用std:acculate使用方法2编译。为什么? #include <vector> #include <numeric> #include <stdlib.h> #include <functional> #include <iostream> using namespace std; class Raven{ public:
#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;
};
您的问题是Raven::sum_life是一个成员函数。 谢天谢地,您可以使用并传递“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();
sum_life是一个成员函数,因此正在寻找一个成员参数(这很糟糕)。将sum_life设置为静态。更好的方法是使用boost::Make_transform_iterator()在每次读取迭代器时自动访问get_lifespan()方法。
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();