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頁面存檔備份,存於互聯網檔案館

    外部連結[編輯]