當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ std::accumulate()用法及代碼示例

C++ STL 支持多種函數和模板,以不同的方式解決問題。

C++ STL std::accumulate() 函數

std::accumulate() 函數用於累加所有的值range [first, last]包括任何變量initial_sum

累積函數 do 的默認操作是將所有元素相加,但可以執行不同的操作。

accumulate() 函數的語法:

    accumulate(start, end, initial_sum);

這裏,

  • start:是迭代器的初始位置
  • end: 是迭代器的最後一個位置。

注意:還可以在累加函數中傳遞一個附加參數,該參數指定要執行的操作類型。

帶有附加參數的 accumulate() 函數的語法:

    accumulate(start, end, initial_sum, func);

這裏,func是要執行的附加操作。

C++程序演示std::accumulate()函數的例子

#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;
}

輸出

 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


相關用法


注:本文由純淨天空篩選整理自 std::accumulate() function with example in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。