您的位置:首页 > 其它

泛型算法系列25:inner_product()

2009-08-18 11:11 218 查看
#include <numeric>
#include <vector>
#include <iostream>

using namespace std;
/************************************************************************/
/*                                                                      */
/************************************************************************/
template<class _InIt1, class _InIt2, class _Ty>
inline
_Ty my_Inner_product(_InIt1 _First1, _InIt1 _Last1, _InIt2 _First2, _Ty _Val)
{	// return inner product of sequences
_DEBUG_RANGE(_First1, _Last1);
for (; _First1 != _Last1; ++_First1, ++_First2)
_Val = _Val + *_First1 * *_First2;
return (_Val);
}
/************************************************************************/
/*                                                                      */
/************************************************************************/
template<class _InIt1, class _InIt2, class _Ty, class _Fn21, class _Fn22>
inline
_Ty my_Inner_product(_InIt1 _First1, _InIt1 _Last1, _InIt2 _First2, _Ty _Val,
_Fn21 _Func1, _Fn22 _Func2)
{	// return inner product of sequences, using _Func1 and _Func2
_DEBUG_RANGE(_First1, _Last1);
_DEBUG_POINTER(_Func1);
_DEBUG_POINTER(_Func2);
for (; _First1 != _Last1; ++_First1, ++_First2)
_Val = _Func1(_Val, _Func2(*_First1, *_First2));
return (_Val);
}
int main()
{
int ia[] =  { 2, 3, 5, 8 };
int ia2[] = { 1, 2, 3, 4 };
// multiply the element pair from the two arrays
// then add to the initial value: 0
int res = my_Inner_product( &ia[0], &ia[4], &ia2[0], 0);
// generates: inner product of arrays: 55
cout << "inner product of arrays: "
<<  res  <<  endl;
vector<int> vec(  ia,  ia + 4 );
vector<int> vec2( ia2, ia2 + 4 );
// add the element pair from the two vectors
// then subtract from the initial value: 0
res = my_Inner_product( vec.begin(), vec.end(),
vec2.begin(), 0,
minus<int>(),
plus<int>() );
// generates: inner product of vectors:  -28
cout<<"inner product of vectors: "
<< res << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: