accumulate
被计算顺序部分计算和所有元素的总和在指定的范围中包括某些初始值或计算从使用的指定二进制操作类似获取的顺序部分结果除和之外。
template<class InputIterator, class Type>
Type accumulate(
InputIterator _First,
InputIterator _Last,
Type _Val
);
template<class InputIterator, class Type, class BinaryOperation>
Type accumulate(
InputIterator _First,
InputIterator _Last,
Type _Val,
BinaryOperation _Binary_op
);
参数
_First
解决在范围的输入迭代器第一个元素将进行求和或合并根据的指定二进制操作。_Last
解决在范围的输入迭代器个元素将进行求和或合并根据超出最终元素外的位置中的指定二进制操作在循环访问的累计实际包含的。_Val
每个元素反过来添加或合并。根据的指定二进制操作的初始值。_Binary_op
将应用到指定的范围、其以前应用程序中的每个元素的结果二进制操作。
返回值
_Val 以及所有元素的总和在指定范围内第一个模板函数或的,第二个模板函数的,二进制应用指定操作的结果,而不是操作,总和为 (PartialResult,*Iter),其中是操作 PartialResult 和 Iter 的前应用程序的结果是一个指向元素的迭代器在范围。
备注
初始值确保具有显式定义的结果,在范围为空时,在这种情况下,_Val 返回条件下。 二进制操作不是必需或关联可交换的。 结果初始化初始值为 _Val = _Binary_op,然后 结果 (结果###*Iter) 通过迭代范围计算,Iter 是指向在范围的连续元素的迭代器。 范围绑定有效,而复杂是线性的使用范围的大小。 二元运算符的返回类型必须可转换为 类型 迭代过程确保关闭。
示例
// numeric_accum.cpp
// compile with: /EHsc
#include <vector>
#include <numeric>
#include <functional>
#include <iostream>
int main( )
{
using namespace std;
vector <int> v1, v2(20);
vector <int>::iterator iter1, iter2;
int i;
for (i = 1; i < 21; i++)
{
v1.push_back(i);
}
cout << "The original vector v1 is:\n ( " ;
for (iter1 = v1.begin(); iter1 != v1.end(); iter1++)
cout << *iter1 << " ";
cout << ")." << endl;
// The first member function for the accumulated sum
int total;
total = accumulate(v1.begin(), v1.end(), 0);
cout << "The sum of the integers from 1 to 20 is: "
<< total << "." << endl;
// Constructing a vector of partial sums
int j = 0, partotal;
for (iter1 = v1.begin(); iter1 != v1.end(); iter1++)
{
partotal = accumulate(v1.begin(), iter1 + 1, 0);
v2[j] = partotal;
j++;
}
cout << "The vector of partial sums is:\n ( " ;
for (iter2 = v2.begin(); iter2 != v2.end(); iter2++)
cout << *iter2 << " ";
cout << ")." << endl << endl;
// The second member function for the accumulated product
vector <int> v3, v4(10);
vector <int>::iterator iter3, iter4;
int s;
for (s = 1; s < 11; s++)
{
v3.push_back(s);
}
cout << "The original vector v3 is:\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 << "The product of the integers from 1 to 10 is: "
<< ptotal << "." << endl;
// Constructing a vector of partial products
int k = 0, ppartotal;
for (iter3 = v3.begin(); iter3 != v3.end(); iter3++) {
ppartotal = accumulate(v3.begin(), iter3 + 1, 1, multiplies<int>());
v4[k] = ppartotal;
k++;
}
cout << "The vector of partial products is:\n ( " ;
for (iter4 = v4.begin(); iter4 != v4.end(); iter4++)
cout << *iter4 << " ";
cout << ")." << endl;
}
要求
数字 <的页眉: >
命名空间: std