在类成员函数中累积同一类的对象
Accumulate objects of the same class within a class member function
我有以下类。当我用方法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();
相关文章:
- 如何创建从同一类继承的不同对象的向量
- 在 c++ 中将对象设置为等于同一类的构造函数是否有效?
- 同一类的两个对象相互引用
- 打印同一类中的 3 个对象
- 在 c++ 中,同一类的一个对象如何分配给同一类的另一个对象?
- 如何在C++中将类的实例完全重新分配给同一类的另一个实例(然后删除原始对象)?
- 如何重载"<"运算符以比较同一类的对象?
- 将来自类的对象用作另一类C 类的对象
- 修改对象也会修改同一类的所有其他对象
- 在另一类中使用受保护的破坏者删除对象
- 如何使用箭头指针打印出一类数组对象,这些对象中有多个分数
- 如何为同一类对象的成员函数保留单独的变量副本?
- 如何将成员函数用于同一类的不同对象
- 如何使用nullptr初始化同一类对象的静态指针数组?
- 一类应管理其实例化对象
- 如何重载赋值运算符以满足 ob1=ob2=ob3(ob1,ob2,ob3 是同一类的对象)
- C++:按值将对象传递给同一类的成员函数
- 有什么方法可以测试来自同一类的两个作业对象吗
- C++类构造函数使用指向同一类对象的指针
- C++如何共享同一类对象中的公共元素