stl算法之accumulate

本文探讨了C++中使用`std::accumulate`进行默认累加、累减及自定义规则的性能,发现`accumulate`在容器操作上效率较高,但在普通数组上循环可能更快。通过实例展示了不同累加方式的应用与结果。
摘要由CSDN通过智能技术生成

首先包含#include<numeric>
然后看看代码:

1.先看看累加

void main()
{

	//1.默认累加
	std::vector<int> a(100000, 1);

	a[2] = 2;
	a[3] = 2;
	a[4] = 3;
	
	clock_t t1 = clock();
	int nsum = accumulate(begin(a), end(a), 0);//0   +1+2+3+4+5+6+7+0+0+0+0...
	clock_t t2 = clock();
	cout << "nsum:" << nsum << " time:"<<t2-t1<<endl;

	int nsum2 = accumulate(begin(a), end(a), 10);//10   +1+2+3+4+5+6+7+0+0+0+0...
	cout << "nsum2:"<<nsum2 << endl;

	int nsum3 = 0;
	clock_t t3 = clock();

	for (int i = 0; i < 100000; i++)
	{
		nsum3 += a[i];
	}
	clock_t t4 = clock();
	cout << "nsum3:" << nsum3 << " time:" << t4 - t3 << endl;

	system("pause");
}

结果:
在这里插入图片描述
从结果可以看出使用accumulate的算法比传统循环累加需要的时间少。所以推介使用但仅是容器的情况下快,我在测试普通数组的时候,反而循环更快。

2.累减

int nsum4 = accumulate(begin(a), end(a), 0,minus<int>());//0-1-1-1-1-1-...
cout << "num4:"<<nsum4 << endl;

int nsum5 = accumulate(begin(a), end(a), 5, minus<int>());//5-1-1-1-1-1-...
cout << "num5:" << nsum5 << endl;

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

3.自定义累加规则

int nsum6 = accumulate(begin(a), end(a), 0, [](int x, int y){return x + 2 * y; });//0-1-1-1-1-1-...
	cout << "num6:" << nsum6 << endl;

	int nsum7 = accumulate(begin(a), end(a), 2, [](int x, int y){return x + 2 * y; });//0-1-1-1-1-1-...
	cout << "num7:" << nsum7 << endl;

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

发如雪-ty

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

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

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

打赏作者

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

抵扣说明:

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

余额充值