/*
*Copyright(c) 2016, 烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:main.cpp
*作 者:李德坤
*完成日期:2016年6月4日
*版本号:v1.0
*
*问题描述:阅读程序(3)
*输入描述:无
*输出描述:无
*/
#include <algorithm>
#include <functional>
#include <vector>
#include <iostream>
#include <numeric>
#include <iterator>
using namespace std;
int main()
{
int a[] = {1,4,7,2,5,8};
int b[] = {1,2,3,3,2,1};
const int ASZ = sizeof a / sizeof a[0];//ASZ=6
const int BSZ = sizeof b / sizeof b[0];//BSZ=6
ostream_iterator<int> out(cout," ");//定义输出迭代器
copy(a, a + ASZ, out);//输出数组a
cout<<endl;
copy(b, b + BSZ, out);//输出数组b
cout<<endl;
int r = accumulate(a, a + ASZ, 0);//r=0+1+4+7+2+5+8=27
cout << "accumulate 1: " << r << endl;
// Should produce the same result:
r = accumulate(b, b + BSZ, 0, plus<int>());//0+1+2+3+3+2+1=12
cout << "accumulate 2: " << r << endl;
r = inner_product(a, a + ASZ, b, 0);
// 或 r = inner_product(a, a + ASZ, b, 0, plus<int>(), multiplies<int>());
//inner_product返回作为两个序列乘积而生成的元素的总和。步调一致地检查两个序列,将
//来自两个序列的元素相乘,将相乘的结果求和。由 init 指定和的初值。假定从
//beg2 开始的第二个序列具有至少与第一个序列一样多的元素,忽略第二个序列
//中超出第一个序列长度的任何元素。init 的类型决定返回类型。
cout << "inner_product : " << r << endl;
int* it = partial_sum(a, a + ASZ, b);
// 或 int* it = partial_sum(a, a + ASZ, b, plus<int>());
//a,a+ASZ是输入序列,b是输出序列
//将输入序列中每个元素与其先前所有元素的和写入对应位置的输出序列中.
copy(b, it, out);//输出b
cout<<endl;
it = adjacent_difference(a, a + ASZ, b);
// 或 it = adjacent_difference(a, a + ASZ, b, minus<int>());
//对于给定的序列x0,x1,...,x(n-1),计算序列中相邻两个元素的差序列x1-x0,x2-x1,...,x(n-1)-x(n-2)。该算法可以把结果序列保存在原序列中,也可以保存在另一个区间中。
//除了比较出差值,还可以作给定的交互。
//第一个元素是不变的放入结果中的。
//adjacent_difference() 是数值算法,使用 <numeric> 头文件。
copy(b, it, out);//输出b
cout<<endl;
return 0;
}
/*
输出结果为:
1 4 7 2 5 8
1 2 3 3 2 1
accumulate 1: 27
accumulate 2: 12
inner_product : 54
1 5 12 14 19 27
1 3 3 -5 3 3
*/