inner_product |
Calculate the inner product of two sequences.
Use a pair of iterators i
and j to traverse the two sequences [
first1...last1 ) and [ first2...first2 +
( last1 - first1
)). Apply the formula init = init
op1 ( * i
op2 *
j ) and return the final value of init
. Note that init is not automatically initialized to
zero prior to this operation. The first version automatically sets op1
to operator+ and op2 to operator*
.
#include <numeric>
template< class InputIterator1, class InputIterator2, class T >
T inner_product
(
InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
T init
);
template
<
class InputIterator1,
class InputIterator2,
class T,
class BinaryOperation1,
class BinaryOperation2
>
T inner_product
(
InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
T init,
BinaryOperation1 op1,
BinaryOperation2 op2
);
Time complexity is linear. Space complexity is constant.
#include <iostream>
#include <numeric>
int numbers1[ 5 ] = { 1, 2, 3, 4, 5 };
int numbers2[ 5 ] = { 1, 2, 3, 4, 5 };
void
main()
{
int result;
result = inner_product( numbers1, numbers1 + 5, numbers2, 0 );
cout << "Inner product = " << result << "\n";
}
Inner product = 55
#include <iostream>
#include <iterator>
#include <vector>
#include <numeric>
void
main()
{
vector< int > v1( 3 );
vector< int > v2( v1.size() );
for ( size_t i = 0; i < v1.size(); ++i )
{
v1[ i ] = i + 1;
v2[ i ] = v1.size() - i;
}
ostream_iterator< int > iter( cout, " " );
cout << "Inner product sum of products ) of:\n\t";
copy( v1.begin(), v1.end(), iter );
cout << "\n\t";
copy( v2.begin(), v2.end(), iter );
int result = inner_product( v1.begin(), v1.end(), v2.begin(), 0 );
cout << "\nis: " << result << "\n";
}
Inner product (sum of products) of:
1 2 3
3 2 1
is: 10
#include <iostream>
#include <iterator>
#include <vector>
#include <numeric>
int
add( int a_, int b_ )
{
return a_ + b_;
}
int
mult( int a_, int b_ )
{
return a_ * b_;
}
void
main()
{
vector< int > v1( 3 );
vector< int > v2( v1.size() );
for ( size_t i = 0; i < v1.size(); ++i )
{
v1[ i ] = i + 1;
v2[ i ] = v1.size() - i;
}
ostream_iterator< int > iter( cout, " " );
cout << "Inner product( product of sums ):\n\t";
copy( v1.begin(), v1.end(), iter );
cout << "\n\t";
copy( v2.begin(), v2.end(), iter );
int result = inner_product
(
v1.begin(),
v1.end(),
v2.begin(),
1,
mult,
add
);
cout << "\nis: " << result << "\n";
}
Inner product (product of sums) of:
1 2 3
3 2 1
is: 64
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.