STL中accumulate函数的使用

#pragma warning (disable : 4786)

#include <iostream>
#include <numeric>
#include <functional>
#include <vector>
#include <iterator>
#include <string>

#if _MSC_VER > 1020 // if VC++ version is > 4.2
using namespace std; // std c++ libs implemented in std
#endif

typedef vector < float, allocator < float > > FloatArray;
typedef vector < string, allocator < string > > StringArray;
typedef ostream_iterator <float, char, char_traits <char> >
FloatOstreamIt;

void main ()
{
// a vector of floats
FloatArray rgFA;

// an ostream iterator that outputs a float to cout terminated
// by a space
FloatOstreamIt OstreamIt(cout," ");

// Initialize the array to 1,1/2,1/3,...
for (int i=0; i<10; i++) rgFA.push_back(1.0f/(i+1));

// Print the array
copy(rgFA.begin(),rgFA.end(),OstreamIt);
cout << endl;

// Sum the array
cout << "The sum of 1 + 1/2 + 1/3 + ... + 1/10 is "
<< accumulate(rgFA.begin(),rgFA.end(),0.0f)
<< endl;

// Compute the product of the array
cout << "The product of 1 * 1/2 * 1/3 * ... * 1/10 is "
<< accumulate(rgFA.begin(),rgFA.end(),1.0f,multiplies<float>())
<< endl;

// Initialize array of strings
StringArray rgs;
rgs.push_back("This ");
rgs.push_back("is ");
rgs.push_back("one ");
rgs.push_back("sentence. ");

// Concatenate the strings in the array & print the sentence
cout << "The concatenated vector of strings: "
<< accumulate(rgs.begin(),rgs.end(),string(""))
<< endl;
}



程序输出为:

1 0.5 0.333333 0.25 0.2 0.166667 0.142857 0.125 0.111111 0.1
The sum of 1 + 1/2 + 1/3 + ... + 1/10 is 2.92897
The product of 1 * 1/2 * 1/3 * ... * 1/10 is 2.75573e-007
The concatenated vector of strings: This is one sentence.

以下网址可参考:

http://topic.csdn.net/u/20080531/00/f1595d26-60e2-4aa9-9263-80d4755dd31e.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值