accumulate 函数
C++ STL supports a variety of functions and templates to solve problems in different ways.
C ++ STL支持多种功能和模板,以不同方式解决问题。
C ++ STL std :: accumulate()函数 (C++ STL std::accumulate() function)
std::accumulate() function is used to accumulate all the values in the range [first, last] both inclusive to any variable initial_sum.
std :: accumulate()函数用于累积[first,last]范围内的所有值,包括所有变量initial_sum 。
Default operation which accumulates function do is adding up all the elements but different operations can be performed.
累积功能的默认操作是将所有元素加在一起,但是可以执行不同的操作。
Syntax of accumulate() function:
accumulate()函数的语法:
accumulate(start, end, initial_sum);
Here,
这里,
start: is the initial position of the iterator
start :是迭代器的初始位置
end: is the last position of the iterator.
end :是迭代器的最后一个位置。
Note: An additional argument can also be passed in the accumulate function which specifies the type of operation to be performed.
注意:还可以在accumulate函数中传递一个附加参数,该参数指定要执行的操作的类型。
Syntax of accumulate() function with additional argument:
带有其他参数的accumulate()函数的语法:
accumulate(start, end, initial_sum, func);
Here, func is the additional operation which is to be performed.
在这里, func是要执行的附加操作。
C ++程序演示std :: accumulate()函数的示例 (C++ program to demonstrate example of std::accumulate() function)
#include <bits/stdc++.h>
#include <vector>
using namespace std;
int main()
{
// Initialization of vector
vector<int> vec{1,2,3,4,5,6,7,8,9};
// Taking initial sum as 0
int sum = 0;
cout << "\n Initial value of sum = " << sum << endl;
// Demonstration of accumulate function
// to sum all the elements of the vector
sum = accumulate(vec.begin(), vec.end(), sum);
cout << " Value of sum after accumulate = " << sum << endl;
// Changing value of initial_sum to 50
sum = 50;
cout << "\n Initial value of sum = " << sum << endl;
// Demonstration of accumulate function
// with the additional argument
// Here additional argument is used to
// subtract all the elements from the
// initial sum. Additional argument can be
// any valid function or operation
sum = accumulate(vec.begin(), vec.end(), sum, minus<int>());
cout << " Value of sum after accumulate function with optional argument = " << sum << endl;
return 0;
}
Output
输出量
Initial value of sum = 0
Value of sum after accumulate = 45
Initial value of sum = 50
Value of sum after accumulate function with optional argument = 5
翻译自: https://www.includehelp.com/stl/std-accumulate-function-wit-example-in-cpp-stl.aspx
accumulate 函数