// inner_product.cpp -- 2011-10-05-17.07
#include "stdafx.h"
#include <iostream>
#include <numeric>
#include <vector>
#include <functional>
using std ::vector ;
using std ::plus ;
using std ::multiplies ;
template<class T>
class Print
{
public:
void operator () (const T & t) const
{
std ::cout << t << " " ;
}
} ;
int _tmain(int argc, _TCHAR* argv[])
{
int arr1[] = {1, 2, 3, 4} ;
vector<int> vec1(arr1, arr1 + sizeof arr1 / sizeof (int)) ;
int arr2[] = {1, 1, 1, 2} ;
vector<int> vec2(arr2, arr2 + sizeof arr2 / sizeof (int)) ;
// inner_product (beg1, end1, beg2, init) ;
// 操作前:[beg1,end1)和[beg2,...)标示输入序列.init是第一个参与运算的值.
// 操作后:计算init依次加两个输入序列各自对应元素的乘积.
// 返回值:计算所得的值.
// 备注: init是第一个参与运算的元素.init的类型决定返回值的类型.
// [beg2,...)序列至少同[beg1,end1)序列一样大.否则将抛出异常.
// [beg2,...)中超出[beg1,end1)长度的序列不参与运算.
int totalValue = inner_product(vec1.begin(), vec1.end(), vec2.begin(), 0) ;
std ::cout << totalValue << std ::endl ;
// inner_product (beg1, end1, beg2, init, plus<int> (), multiplies<int> ()) ;
// 操作前:[beg1,end1)和[beg2,...)标示输入序列.init是第一个参与运算的值.plus<int> ()和multiplies<int> ()是二元函数对象.
// 操作后:计算init依次加两个输入序列各自对应元素的乘积.
// 返回值:计算所得的值.
// 备注: init是第一个参与运算的元素.init的类型决定返回值的类型.
// [beg2,...)序列至少同[beg1,end1)序列一样大.否则将抛出异常.
// [beg2,...)中超出[beg1,end1)长度的序列不参与运算.
// plus<int> ()所在位置用来替换不带此参数版本算法的加.
// multiplies<int> ()所在位置用来替换不带此参数版本算法的乘.
totalValue = inner_product(vec1.begin(), vec1.end(), vec2.begin(), 0, plus<int> (), multiplies<int> ()) ;
std ::cout << totalValue << std ::endl ;
std ::cin.get() ;
std ::cout << std ::endl ;
}
inner_product
最新推荐文章于 2023-04-12 23:57:43 发布