# STL algorithm (1) : numeric part

STL algorithm (1) : numeric part
includes functions: accumulate, partial_sum, adjacent_difference, inner_product

### 1. accumulate

//代码经过vc6.0 调试， 使用SGI-STL3.0 (此版本代码可阅读性比较好，侯先生的<<STL源码剖析>>就是用的此版 本)

#include <numeric>
#include<iostream.h>

template<class T>
struct myFun
{

T operator()(const T& x, const T& y)const
{ return x + 3*y*y -5*y+10; }
};

using namespace  std;
void main()
{
int data[5] = {1, 2, 3, 4, 5};
cout<< accumulate(data, data+5, 0, myFun<int>())<<endl; //140
}

template <class InputIterator, class T>
T accumulate(InputIterator first, InputIterator last, T init);

template <class InputIterator, class T, class BinaryFunction>
T accumulate(InputIterator first, InputIterator last, T init,
BinaryFunction binary_op);

### 2.partial_sum 部分和

∑（3Xi2-5Xi+10）  i∈[1, k] , k ∈[1, 5]

#include <numeric>
#include<iostream>
#include <algorithm>

template<class T>
struct myFun
{

T operator()(const T& x, const T& y)const
{ return x + 3*y*y -5*y+10; }
};

using namespace  std;
void main()
{
int data[5] = {1, 2, 3, 4, 5};
partial_sum (data, data+5, data, myFun<int>());
copy (data, data+5, ostream_iterator<int>(cout, "* "));  //1* 13* 35* 73* 133*
cout<<endl;
}

template <class InputIterator, class OutputIterator>
OutputIterator partial_sum(InputIterator first, InputIterator last,
OutputIterator result);

template <class InputIterator, class OutputIterator, class BinaryOperation>
OutputIterator partial_sum(InputIterator first, InputIterator last,
OutputIterator result, BinaryOperation binary_op);


yi =xi2-5xi-1+10 ,    ( i∈[2, 5] , y1=x1)

#include <numeric>
#include<iostream>
#include <algorithm>

template<class T>
struct myFun
{
T operator()(const T& x, const T& y)const
{ return x*x - 5*y + 10; }
};

using namespace  std;
void main()
{
int data[5] = {1, 2, 3, 4, 5};
copy (data, data+5, ostream_iterator<int>(cout, "* "));  //1* 9* 9* 11* 15*
cout<<endl;
}

template <class InputIterator, class OutputIterator>
OutputIterator result);

template <class InputIterator, class OutputIterator, class BinaryFunction>
OutputIterator result,
BinaryFunction binary_op);


### 4.inner_product 内积

用途: 计算两个序列的统计特性。

X[n] = {1, 2, 3, 4, 5}；

Y[n] = {5, 4, 3, 2 ,1};

∑(xi2-5Yi+10 ),    ( i∈[1, 5] )

#include <numeric>
#include<iostream>
#include <algorithm>

template<class T>
struct myFun
{
T operator()(const T& x, const T& y)const
{ return x*x - 5*y + 10; }
};

using namespace  std;
void main()
{
int x[5] = {1, 2, 3, 4, 5};
int y[5] = {5, 4, 3, 2 ,1};
cout<<inner_product (x, x+5, y, 0, plus<int>(),myFun<int>()) //30
<<endl;
}

1.  accumulate , inner_product 计算序列的一个统计特性数据;