算术生成算法------accumulate

在这里插入图片描述
accumulate
在这里插入图片描述
注意:第三个参数是起始累加值

自定义数据类型的例子:通过accumulate算出年龄综合,求平均年龄

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
#include<numeric>
//自定义数据类型
class person {
    
    
public:
	person(string name, int age) :name(name), age(age) {
    
    }
	int age;
	string name;
	
};
//函数对象
class p {
    
    
public:
	void operator()(person& p1)
	{
    
    
		cout << p1.name << "\t" << p1.age << endl;
	}
};
//普通函数
int acc(int &val,person& p)
{
    
    
	return val += p.age;
}
//函数对象
class add {
    
    
public:
	int operator()(int val, person& p)
	{
    
    
		return val += p.age;
	}
};
void test01()
{
    
    
	person p1("孙悟空1", 18);
	person p2("孙悟空2", 19);
	person p3("孙悟空3", 20);
	person p4("猪八戒1", 21);
	person p5("猪八戒2", 22);
	vector<person> v = {
    
     p1,p2,p3,p4,p5 };
	//年龄累加的起始值是0
	int sum = accumulate(v.begin(), v.end(),0,add());
	cout << "平均年龄为:" << sum / 5;
}
int main()
{
    
    

	test01();
	cout << endl;
	system("pause");
	return 0;
}

在这里插入图片描述
底层代码:
在这里插入图片描述

_val来接收第四个参数里面所填函数或者函数对象的返回值,并且函数里面有两个参数,一个是第三个参数的val,一个是迭代器遍历的容器的元素

猜你喜欢

转载自blog.csdn.net/m0_53157173/article/details/113915412