accumulate
来自cppreference.com
语法:
#include <numeric> T accumulate( input_iterator start, input_iterator end, T val ); T accumulate( input_iterator start, input_iterator end, T val, BinaryFunction f );
accumulate函数计算val与所有在[start,end)范围内的元素的和。
如果二元函数f被指定了, 它会被用作执行计算和的操作。
例如,下面的代码使用了accumulate来计算在 vector中的整数的和:
#include <iostream> using std::cout; #include <vector> using std::vector; #include <numeric> using std::accumulate; int main() { vector<int> v; const int START = 1, END = 10; for( int i = START; i <= END; ++i ) v.push_back(i); int sum = accumulate( v.begin(), v.end(), 0 ); cout << "sum from " << START << " to " << END << " is " << sum << '\n'; }
accumulate函数也可以用在不是数字的类型上。下面的例子就使用了accumulate来连接所有在 vector中的 strings到单个string:
int main () { string str = "Hello World!"; vector<string> vec(10,str); // vec = ["Hello World!", "Hello World!", ...] string a = accumulate( vec.begin(), vec.end(), string("") ); cout << a << endl; // displays "Hello World!Hello World!Hello..." }
[编辑] 复杂度
accumulate函数在 线性时间内完成。