c++ STL accmulate

来源:互联网 发布:mac远程控制 向日葵 编辑:程序博客网 时间:2024/05/20 21:48

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

0 0
原创粉丝点击