C++ STD accumulate函數。本站提示廣大學習愛好者:(C++ STD accumulate函數)文章只能為提供參考,不一定能成為您想要的結果。以下是C++ STD accumulate函數正文
用來計算特定范圍內(包括延續的局部和初始值)一切元素的和,除此之外,還可以用指定的二進制操作來計算特定范圍內的元素後果。其頭文件在numeric中。
用次函數可以求和,結構前n項和的向量,乘積,結構前n項乘積的向量
2. 使用舉例
#include <vector>
#include <numeric>
#include <functional>
#include <iostream>
using namespace std;
int main( )
{
vector <int> v1, v2( 20 );
vector <int>::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 <int> v3, v4( 10 );
vector <int>::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<int>( ) );
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<int>( ) );
v4 [ k ] = ppartotal;
k++;
}
cout << "前n項積辨別為:\n ( " ;
for ( Iter4 = v4.begin( ) ; Iter4 != v4.end( ) ; Iter4++ )
cout << *Iter4 << " ";
cout << ")." << endl;
}
編譯運轉,看一下輸入後果: