C++ Numeric::accumulate() 函式



C++ 的std::complex::accumulate() 函式用於計算範圍內的元素之和或執行其他操作。它接受三個引數:起始和結束迭代器以及累加的初始值。預設情況下,它會將元素新增到初始值,但可以提供自定義二元運算(如乘法或減法)作為第四個引數。

語法

以下是 std::numeric::accumulate() 函式的語法。

T accumulate (InputIterator first, InputIterator last, T init);
or
T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);

引數

  • first, last − 指示序列中初始和最終位置的迭代器。
  • init − 累加器的初始值。
  • binary_op − 二元運算子。

返回值

它返回將範圍 [first,last) 中的所有值累加到 init 的結果。

異常

如果 binary_op、賦值或迭代器上的任何操作丟擲異常,則會丟擲異常。

資料競爭

區域設定物件被修改。

示例 1

在以下示例中,我們將考慮 accumulate() 函式的基本用法。

#include <iostream>
#include <numeric>
#include <vector>
int main() {
   std::vector < int > x = {11,22,3};
   int a = std::accumulate(x.begin(), x.end(), 0);
   std::cout << "Result : " << a << std::endl;
}

輸出

上述程式碼的輸出如下所示:

Result : 36

示例 2

考慮以下示例,我們將對元素進行乘積運算。

#include <iostream>
#include <numeric>
#include <vector>
int main() {
   std::vector < int > a = {11,2,12};
   int x = std::accumulate(a.begin(), a.end(), 1, std::multiplies < int > ());
   std::cout << "Result : " << x << std::endl;
}

輸出

以下是上述程式碼的輸出:

Result : 264

示例 3

讓我們看下面的例子,我們將得到奇數元素的總和。

#include <iostream>
#include <numeric>
#include <vector>
int main() {
   std::vector < int > a = {1,2,3,4,5};
   int x = std::accumulate(a.begin(), a.end(), 0, [](int sum, int x) {
      return x % 2 != 0 ? sum + x : sum;
   });
   std::cout << "Result : " << x << std::endl;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Result : 9
numeric.htm
廣告