zoukankan      html  css  js  c++  java
  • 数值算法速食食谱

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

      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 
    }
  • 相关阅读:
    软件构造 第七章第三节 断言和防御性编程
    软件构造 第七章第二节 错误与异常处理
    软件构造 第七章第一节 健壮性和正确性的区别
    软件构造 第六章第三节 面向可维护的构造技术
    软件构造 第六章第二节 可维护的设计模式
    欧拉函数代码实现及扩展--快速矩阵幂
    编译原理
    算法设计与分析总结
    人工智能简答总结
    感想
  • 原文地址:https://www.cnblogs.com/Zhoier-Zxy/p/8320170.html
Copyright © 2011-2022 走看看