此标头是C ++ STL中数字库的一部分。本文介绍了数字标头中的一些有用功能, 这些功能可在竞争性编程中使用, 以节省时间和精力。
我们通常使用线性运算找出特定范围内或整个数组中元素的总和, 这需要将范围内的所有元素一一相加, 并在每次迭代后将其存储到某个变量中。
此函数返回介于之间的所有值的总和[第一, 最后)与可变的总和。
- 语法1:
accumulate(first, last, sum); first, last : first and last elements of range whose elements are to be added sum : initial value of the sum
- 语法2:此函数返回位于[first, last)与变量sum之间的所有值的和。
accumulate(first, last, sum, myfun); myfun : a function for performing any specific task. For example, we can find product of elements between first and last.
// C++ program to demonstrate working of accumulate()
#include <iostream>
#include <numeric>
using namespace std;
// User defined function
int myfun( int x, int y)
{
// for this example we have taken product
// of adjacent numbers
return x * y ;
}
int main()
{
// Initialize sum = 1
int sum = 1;
int a[] = {5 , 10 , 15} ;
// Simple default accumulate function
cout << "\nResult using accumulate: " ;
cout << accumulate(a , a+3 , sum);
// Using accumulate function with
// defined function
cout << "\nResult using accumulate with"
"user-defined function: " ;
cout << accumulate(a, a+3, sum, myfun);
// Using accumulate function with
// pre-defined function
cout << "\nResult using accumulate with "
"pre-defined function: " ;
cout << accumulate(a, a+3, sum, std::minus< int >());
return 0;
}
输出如下:
Result using accumulate: 31
Result using accumulate with user-defined function: 750
Result using accumulate with pre-defined function: -29
一个示例问题:第k1至第k2个最小元素之间的所有元素的总和
此函数将数组对应元素的部分和分配给第二个数组的每个位置, 并返回介于两个元素之间的所有值的部分和
[第一, 最后)
并将其存储在另一个数组中b。
例如, 如果x表示[first, last)中的元素, 而y表示结果中的元素, 则ys可计算为:
y0 = x0
y1 = x0 + x1
y2 = x0 + x1 + x2
y3 = x0 + x1 + x2 + x3
y4 = x0 + x1 + x2 + x3 + x4
句法 :
partial_sum(first, last, b);
partial_sum(first, last, b, myfun);
first, last : first and last element of range
whose elements are to be added
b : index of array where corresponding partial
sum will be stored;
myfun : a user defined function for performing
any specific task
// C++ program to demonstrate working of accumulate()
#include <iostream>
#include <numeric>
using namespace std;
//user defined function
int myfun( int x, int y)
{
// the sum of element is twice of its
// adjacent element
return x + 2 * y;
}
int main ()
{
int a[] = {1, 2, 3, 4, 5} ;
int b[5];
// Default function
partial_sum(a , a+5 , b);
cout << "Partial Sum - Using Default function: " ;
for ( int i=0; i<5; i++)
cout << b[i] << ' ' ;
cout << '\n' ;
// Using user defined function
partial_sum(a , a+5 , b , myfun) ;
cout << "Partial sum - Using user defined function: " ;
for ( int i=0; i<5; i++)
cout << b[i] << ' ' ;
cout << '\n' ;
return 0;
}
输出:
Partial Sum - Using Default function: 1 3 6 10 15
Partial sum - Using user defined function: 1 5 11 19 29
如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。