C++ Numeric::inner_product() 函式



C++ 的 std::numeric::inner_product() 函式用於返回兩個範圍的內積(點積)。它接受兩個範圍,並返回對應元素乘積的總和。它還接受一個初始值以及用於加法和乘法的自定義二元運算。

語法

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

	
inner_product (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init);
or
inner_product (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2);

引數

  • first1, last1 − 指示序列中初始和最終位置的迭代器。
  • init − 累加器的初始值。
  • binary_op1,binary_op2 − 二元運算。

返回值

它返回累加 init 和從 first1 和 first2 開始的範圍中所有元素對的乘積的結果。

異常

如果元素或迭代器上的任何操作丟擲異常,則丟擲異常。

資料競爭

訪問範圍 [first1,last1) 中的元素。

示例 1

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

#include <iostream>
#include <numeric>
#include <vector>
int main() {
   std::vector < int > x = {1,2};
   std::vector < int > x1 = {3,4};
   int y = std::inner_product(x.begin(), x.end(), x1.begin(), 0);
   std::cout << "Result : " << y << std::endl;
   return 0;
}

輸出

以上程式碼的輸出如下:

Result : 11

示例 2

考慮以下示例,我們將使用不同的初始值並觀察輸出。

#include <iostream>
#include <numeric>
#include <vector>
int main() {
   std::vector < int > a = {1,3};
   std::vector < int > b = {5,7};
   int x = std::inner_product(a.begin(), a.end(), b.begin(), 4);
   std::cout << "Result : " << x << std::endl;
   return 0;
}

輸出

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

Result : 30

示例 3

讓我們看下面的例子,我們將使用自定義二元運算。

#include <iostream>
#include <numeric>
#include <vector>
int main() {
   std::vector < int > x = {2,6};
   std::vector < int > y = {4,8};
   int a = std::inner_product(x.begin(), x.end(), y.begin(), 10, std::minus < int > (), std::divides < int > ());
   std::cout << "Result : " << a << std::endl;
   return 0;
}

輸出

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

Result : 10
numeric.htm
廣告

© . All rights reserved.