当以迭代器first和last及值init作为参数调用时
accumulate(first,last, init);将把init 和从 first 到last 指向的值进行累加,并返回累加得到的和,但不包括last指向的值。通过实例学习accumulate 函数。
#include
#include
#include
using namespace std;
int main()
{
cout<<"Demonstratint the accumulatefunction."<vectorl(&x[0],&x[5]);
int sum = accumulate(vectorl.begin(),vectorl.end(),0);
cout<<"sum ="<vectorl1(&y[0],&y[5]);
double sum2 = accumulate(vectorl1.begin(),vectorl1.end(),0.0);
cout<<"sum2 = "<
结果是
Demonstratint the accumulate function.
sum = 28
sum1 = 28
sum2 = 28.523
#include
#include
#include
#include
using namespace std;
int mult(int x, int y)
{
return x * y;
}
int main()
{
int x[5] = {2, 3, 5, 7, 11};
vectorvectorl(&x[0], &x[5]);
int product = accumulate(vectorl.begin(), vectorl.end(), 1, mult);
cout<<"product = "<
结果为
product = 2310
这里传递给accumulate 函数一个普通函数 mult ,实际上传递的是该函数的地址。
#include
#include
#include
#include
using namespace std;
int main()
{
int x[5] = {2, 3, 5, 7, 11};
vectorvectorl(&x[0], &x[5]);
int product = accumulate(vectorl.begin(), vectorl.end(), 1,multiplies());
cout<<"product = "<
结果为
product = 2310
通过multiplies
multiplies头文件为#include
一个实例在 http://www.linuxidc.com/Linux/2015-04/116423.htm 搬过来学习。
#include
#include
#include
#include
using namespace std;
int main( )
{
vector v1, v2( 20 );
vector ::iterator Iter1, Iter2;
int i;
for ( i = 1 ; i < 21 ; i++ )
{
v1.push_back( i );
}
cout << "最初向量v1中个元素的值为:\n ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")." << endl;
// accumulate函数的第一个功能,求和
int total;
total = accumulate ( v1.begin ( ) , v1.end ( ) , 0 );
cout << "整数从1到20的和为: "
<< total << "." << endl;
// 构造一个前n项和的向量
int j = 0, partotal;
for ( Iter1 = v1.begin( ) + 1; Iter1 != v1.end( ) + 1 ; Iter1++ )
{
partotal = accumulate ( v1.begin ( ) , Iter1 , 0 );
v2 [ j ] = partotal;
j++;
}
cout << "前n项和分别为:\n ( " ;
for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ )
cout << *Iter2 << " ";
cout << ")." << endl << endl;
// accumulate函数的第二个功能,计算连乘积
vector v3, v4( 10 );
vector ::iterator Iter3, Iter4;
int s;
for ( s = 1 ; s < 11 ; s++ )
{
v3.push_back( s );
}
cout << "向量v3的初始值分别为:\n ( " ;
for ( Iter3 = v3.begin( ) ; Iter3 != v3.end( ) ; Iter3++ )
cout << *Iter3 << " ";
cout << ")." << endl;
int ptotal;
ptotal = accumulate ( v3.begin ( ) , v3.end ( ) , 1 , multiplies( ) );
cout << "整数1到10的连乘积为: "
<< ptotal << "." << endl;
// 构造一个前n项积的向量
int k = 0, ppartotal;
for ( Iter3 = v3.begin( ) + 1; Iter3 != v3.end( ) + 1 ; Iter3++ ) {
ppartotal = accumulate ( v3.begin ( ) , Iter3 , 1 , multiplies( ) );
v4 [ k ] = ppartotal;
k++;
}
cout << "前n项积分别为:\n ( " ;
for ( Iter4 = v4.begin( ) ; Iter4 != v4.end( ) ; Iter4++ )
cout << *Iter4 << " ";
cout << ")." << endl;
}
刚开始学习STL,当做记笔记了!!!