The C++ std::numeric::inner_product() function is used to return the inner product (dot product) of two ranges. It takes two ranges and return the sum of the product of the corresponding elements. It also accepts an initial value and custom binary operations for addition and multiplication.
SyntaxFollowing is the syntax for std::numeric::inner_product() function.
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);Parameters
It returns the result of accumulating init and the products of all the pairs of elements in the ranges starting at first1 and first2.
ExceptionsIt throws if any of the operations on the elements or iterators throws.
Data racesThe elements in the range [first1,last1) are accessed.
Example 1In the following example, we are going to consider the basic usage of the inner_product() function.
#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; }Output
Output of the above code is as follows −
Result : 11Example 2
Consider the following example, where we are going to use the different initial value and observing the output.
#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; }Output
If we run the above code it will generate the following output −
Result : 30Example 3
Let's look at the following example, where we are going to use the custom binary operation.
#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; }Output
Following is the output of the above code −
Result : 10
numeric.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4