stl accumulate

这篇博客介绍了STL中的accumulate函数,用于对序列进行求和操作。示例包括对整数向量的求和、字符串连接以及自定义类型(如求年龄总和)。此外,还展示了如何使用自定义操作符实现求积和求自定义属性的总和。

stl中accumulate可以用于求和,如下:

包含:#include <numeric>
1.函数原型:

accumulate(_InIt _First, _InIt _Last, _Ty _Val)

accumulate带有三个形参:头两个形参指定要累加的元素范围,第三个形参则是累加的初值。

accumulate函数将它的一个内部变量设置为指定的初始值,然后在此初值上累加输入范围内所有元素的值。accumulate算法返回累加的结果,其返回类型就是其第三个实参的类型。
2.普通类型:

void main()
{
	std::vector < int > v{1, 3, 5, 7, 9};
	int nsum = std::accumulate(v.begin(), v.end(), 0);
	cout << nsum << endl;

	std::vector<string> vs{ "abc", "def", "ghi", "jkl" };
	string strRes = std::accumulate(vs.begin(), vs.end(), string(""));
	cout << strRes.c_str() << endl;

int a = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());//求积,可以用来计算存储大小,第三个参数表示求积的初值	
	cout << a << endl;
	system("pause");
}

结果:
在这里插入图片描述

3.自定义类型:

class person
{
public:
	person(string na, int age)
	{
		name = na;
		nage = age;
	}
	void show()
	{
		cout << name.c_str() << " " << nage << endl;
	}
	~person()
	{
		cout << "~person()\n";
	}
	int GetAge()
	{
		return nage;
	}
private:
	string name;
	int nage;
};


void main()
{
	std::vector<person> vp{ person("he", 12), person("he", 13), person("he", 14), person("he", 15) };
	int nsumx = std::accumulate(vp.begin(), vp.end(),0, [](int a, person p){return a + p.GetAge(); });
	cout << nsumx << endl;
	system("pause");
}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发如雪-ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值