Boost (C++函数库)

维基百科,自由的百科全书
(重定向自Boost C++ Libraries
跳转到导航 跳转到搜索
Boost C++ Libraries
File:Boost.png
当前版本1.80.0(2022年8月10日,​3年前​(2022-08-10
源代码库
  • {{URL|example.com|可选的显示文本}}
Module:EditAtWikidata第29行Lua错误:attempt to index field 'wikibase' (a nil value)
引擎
    Module:EditAtWikidata第29行Lua错误:attempt to index field 'wikibase' (a nil value)
    类型函数库
    许可协议Boost许可证
    网站www.boost.org

    Boost C++ 函数库(Libraries)是一组扩展C++功能的经过同行评审(Peer-reviewed)且开放源码程序库。大多数的函数为了能够以开放源码或者封闭项目的方式运作,而许可于Boost软件许可协议(Boost Software License)之下。许多Boost的开发人员是来自C++标准委员会,而部分的Boost函数库成为C++的TR1标准之一。[1]

    为了要确保函数库的效率与弹性,Boost广泛的使用C++模板功能。而它是针对各式领域的C++用户与应用领域(Application Domain)上,包含的函数库类别从smart_ptr[2]这种类通用函数库,到boost-filesystem[3]这种文件系统操作系统抽象层,甚至能够利用Boost来开发额外的函数库或是给高级的C++用户利用,例如MPL[4]

    内容[编辑]

    范例[编辑]

    现有的 Boost 包含大约150种不同的函数库,以下面几项做范例:

    线性代数 – uBLAS[编辑]

    Boost 包含了 uBLAS 线性代数函数库,能够借由基本函数库子函数(BLAS)来支持向量与矩阵形运算。

    • 此范例表示如何矩阵与向量作乘积:
     
    #include <boost/numeric/ublas/vector.hpp>
    #include <boost/numeric/ublas/matrix.hpp>
    #include <boost/numeric/ublas/io.hpp>
    #include <iostream>
    
    using namespace boost::numeric::ublas;
    
    /* 举例 "y = Ax"  */
    int main () 
    {
          vector<double> x (2);
          x(0) = 1; x(1) = 2;
     
          matrix<double> A(2,2);
          A(0,0) = 0; A(0,1) = 1;
          A(1,0) = 2; A(1,1) = 3;
    
          vector<double> y = prod(A, x);
    
          std::cout << y << std::endl;
          return 0;
    }
    

    随机数产生 – Boost.Random[编辑]

    Boost 也提供独立分布的模拟随机与 PRNG 独立性的机率分布,而这些能够具体的建立产生器。

    #include <boost/random.hpp>
    #include <ctime>
    
    using namespace boost;
    
    double SampleNormal (double mean, double sigma)
    {
        // 建立一个 Mersenne twister 随机数产生器
        // 使用 Unix 时间设定 seed
        static mt19937 rng(static_cast<unsigned> (std::time(0)));
    
        // 选择高斯机率分布
        normal_distribution<double> norm_dist(mean, sigma);
    
        // 使用 function 的形式,生成随机数据产生器
        variate_generator<mt19937&, normal_distribution<double> >  normal_sampler(rng, norm_dist);
    
        // 传回样本分布结果
        return normal_sampler();
    }
    

    更详细的说明请参阅 Boost 随机数库页面存档备份,存于互联网档案馆)。

    多线程 – Boost.Thread[编辑]

    示例码演示建立线程:

    #include <boost/thread/thread.hpp>
    #include <iostream>
    
    using namespace std; 
    
    void hello_world() 
    {
      cout << "Hello world, I'm a thread!" << endl;
    }
    
    int main(int argc, char* argv[])
    {
      // 開始一條使用 "hello_world" function 的新執行緒
      boost::thread my_thread(&hello_world);
      // 等待執行緒完成工作
      my_thread.join();
      
      return 0;
    }
    

    引用[编辑]

    1. Library Technical Report. [2008-08-07]. (原始内容存档于2017-12-11). 
    2. smart_ptr 函数库页面存档备份,存于互联网档案馆
    3. Boost Filesystem
    4. MPL页面存档备份,存于互联网档案馆

    外部链接[编辑]