C++ STL中的accumulate()和partial_sum()：数字标头

2021年3月12日15:10:37 发表评论 593 次浏览

1. 语法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. 语法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
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``````

[第一, 最后)

``````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
``````// 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
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``````