accumulate

本文介绍了 C++ STL 中的 accumulate 函数,该函数用于计算一系列元素的总和,不仅适用于数值类型,还支持字符串等非数值类型的拼接。通过示例展示了如何使用此函数计算1到100的总和及合并字符串。

accumulate?就是sum up a range of elements。呵呵。这个挺简单的。以下是这个算法的简单介绍:

Syntax:
#include <numeric>//呵呵,使用这个算法这个头文件是必需要包含进来滴!
TYPE accumulate( input_iterator start, input_iterator end, TYPE val );
TYPE accumulate( input_iterator start, input_iterator end, TYPE val, BinaryFunction f );

The accumulate function computes the sum of val and all of the elements in the range [start,end).
If the binary function f is specified, it is used instead of the + operator to perform the summation.
The accumulate function runs in linear time. //我看了非常久,linear time 应该说的这个算法的复杂度是O(n)吧,呵呵~~~百度之貌似没有结果。

 

嗯,废话少说,以下来看它的应用。用这个算法来计算1到100的和。

#include <iostream> #include <vector> #include <numeric> using namespace std; int main() { vector<int> v; const int START = 1, END = 100; for( int i = START; i <= END; ++i ) v.push_back(i);//把1到100压入vector容器中! int sum = accumulate( v.begin(), v.end(), 0 );//就是这个算法,非常奇妙吧。 cout << "sum from " << START << " to " << END << " is " << sum << '/n'; return 0; }

毫无疑问,它的执行结果是"sum from 1 to 100 is 5050"值得注意的是,TYPE accumulate( input_iterator start, input_iterator end, TYPE val );val也是要加进去滴!上面是0,肯定等于没加!

当然,这个程序我们一般用个for循环解决就是,干嘛还要这么大费周折呢。呵呵,事实上 accumulate 可爱的地方不只在于对于数字运算支持,对于非数值运算也是支持的!

The accumulate function can also be used on non-numerical types. The following example uses accumulate to concatenate all of the strings in a vector into a single string:

 

#include <iostream> #include <vector> #include <string> #include <numeric> using namespace std; int main () { string str = "Hello World!"; vector<string> vec(10,str); // vec = ["Hello World!", "Hello World!", ...] string a = accumulate( vec.begin(), vec.end(), string("HaHaHa----") ); cout << a << endl; // displays "HaHaHa----Hello World!Hello World!Hello..." return 0; }

 

呵呵,第一个STL C++ Algorithms accumulate 算法介绍完成!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值