c++ STL accmulate

本文介绍C++标准库中的accumulate函数用法,通过示例展示了如何使用该函数进行求和与乘积运算,并解释了不同重载版本的功能区别。

sum (1)
template <class InputIterator, class T>
   T accumulate (InputIterator first, InputIterator last, T init);
custom (2)
template <class InputIterator, class T, class BinaryOperation>
   T accumulate (InputIterator first, InputIterator last, T init,
                 BinaryOperation binary_op);
第一种形式:对于数列 a1,a2,a3,a4---------运用上述算法的效果为:init +a1+a2+a3+a4

第二种形式:对于数列 a1,a2,a3,a4---------运用上述算法的效果为:init  binary_op a1  binary_op  a2 binary_op a3 binary_op
a4




#include "algostuff.hpp"

#include <iterator>
#include <ostream>
#include <numeric>
using namespace std;


int main(){
vector<int> coll;
INSERT_ELEMENTS(coll,1,9);
PRINT_ELEMENTS(coll);
cout<<endl;


cout<<"sum:"<<accumulate(coll.begin(),coll.end(),0)<<endl;


cout<<"sum:"<<accumulate(coll.begin(),coll.end(),-100)<<endl;


cout<<"product:"<<accumulate(coll.begin(),coll.end(),1,multiplies<int>())<<endl;


cout<<"product:"<<accumulate(coll.begin(),coll.end(),0,multiplies<int>())<<endl;


return 0;

}


编译输出:

1 2 3 4 5 6 7 8 9 
sum:45
sum:-55
product:362880
product:0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值