描述:
將一定內的元素累加,accumulateFunction Computeval與所有在[start,end)範圍內的元素的和。
如果二元函數f被指定了, 它會被用作執行計算和的操作。
文法:
#include <NUMERIC>
T accumulate( input_iterator start, input_iterator end, T val );
T accumulate( input_iterator start, input_iterator end, T val, BinaryFunction f );
Computes the sum of the given value init and the elements in the range [first, last). The first version uses operator+ to sum up the elements, the second version uses the given binary function op.
#include <IOSTREAM>usingstd::cout;#include <VECTOR>usingstd::vector;#include <NUMERIC>usingstd::accumulate; intmain() {vector<INT> v; constintSTART = 1, END = 10;for(inti = START; i <= END; ++i ) v.push_back(i);intsum = accumulate( v.begin(), v.end(), 0 );cout <<"sum from "<< START <<" to " << END << " is "<< sum <<'\n';}
第三個參數是什麼意思呢,我認為應該是初始值,最好寫成(int)0或double(0.0),這一點也在c++primer裡得到了驗證。