accumulate 函数_std :: accumulate()函数以及C ++ STL中的示例

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 函数

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值