数值算法速食食谱

  这次介绍的算法,统称为数值算法。

  STL规定,需使用他们,客户端必须包含表头<numeric>(头文件)。

  SGI将他们实现于<stl_numeric.h>文件中。

  观察这些算法的源代码之前,先示范其用法,是一个比较好的学习方式。以下程序展示该算法每一个详细算法的用途。例中采用ostream_iterator作为输出工具,以后会继续更博介绍,目前请想象它是一个绑定到屏幕的迭代器;只要将任何型别吻合条件的数据结构丢往这个迭代器,便会显示于屏幕上,而这一迭代器会自动跳到下一个可显示位置。

  实现代码及数值算法所要介绍的所有函数算法;

 

#include<numeric>
#include<vector>
#include<functional>
#include<iostream>
#include<iterator>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstdlib>
using namespace std;
int main()
{
    int ia[5] = { 1,2,3,4,5 };
    vector<int> iv(ia,ia+5);
    
    cout << accumulate(iv.begin() ,iv.end(), 0) <<endl;
    //15, i.e. 0 + 1 + 2 + 3 + 4 + 5
    
    cout << accumulate(iv.begin() ,iv.end(), 0, minus<int>()) <<endl;
    //-15, i.e. 0 - 1 - 2 - 3 - 4 - 5
    
    cout << inner_product(iv.begin(), iv.end(), iv.begin(), 10) << endl;
    //65, i.e. 10 + 1*1 + 2*2 + 3*3 + 4*4 + 5*5
    
    cout << inner_product(iv.begin(), iv.end(), iv.begin(), 10, minus<int>(), plus<int>()) << endl;
    //-20, i.e. 10 - 1+1 - 2+2 - 3+3 - 4+4 - 5+5
    
    //以下将这个迭代器绑定到cout,作为输出用
    ostream_iterator<int> oite(cout, " ");
    
     partial_sum(iv.begin(), iv.end(), oite);
     //1 3 6 10 15(新的第n个元素等于前n个元素的相加累计)
     
     partial_sum(iv.begin(), iv.end(), oite, minus<int>());
     //1 -1 -4 -8 -13 (第n个元素是前n个旧元素运算的总计)
     
     adjacent_difference(iv.begin(), iv.end(), oite);
     //1 1 1 1 1(#1元素照录,#n新元素等于#n旧元素 - #n-1旧元素)
     
     cout << power(10,3) << endl;
     //1000, i.e. 10*10*10
     
     cout << power(10,3, plus<int>()) << endl;
     //30, i.e. 10+10+10
     
     int n=3;
     iota(iv.begin(), iv.end(), n);//在指定区间内填入n,n+1,n+2 
     for(int i=0; i<iv.size(); i++)
         cout << iv[i] << ' ';
     //3 4 5 6 7 
}

 

posted @ 2018-01-20 15:28  Zhoier  阅读(220)  评论(0编辑  收藏  举报