C++ Boost Library

Ian Wen

What is this?

C++ Boost Library的簡介

  • C++ 開源函式庫的集合
  • STL 的功能再延伸
  • 104 個不同的 library
  • 20 個分類

簡介

  • 字串和文字處理(String and text processing)
  • 容器(Containers)
  • Iterators
  • 演算法(Algorithms)
  • Function objects and higher-order programming
  • 泛型(Generic Programming)
  • Template Metaprogramming
  • Preprocessor Metaprogramming
  • Concurrent Programming
  • 數學與數字(Math and numerics)

分類們

  • 正確性與測試(Correctness and testing)
  • 資料結構(Data structures)
  • 影像處理(Image processing)
  • 輸入、輸出(Input/Output)
  • Inter-language support
  • 記憶體(Memory)
  • 語法分析(Parsing)
  • 程式介面(Programming Interfaces)
  • 其他雜項
  • Broken compiler workarounds

分類們

安裝

Install C++ Boost Library

# PRESENTING CODE

Linux

ubuntu或wsl

 

macOS

要先裝homebrew

sudo apt install libboost-all-dev
brew install Boost
# PRESENTING CODE

Windows?

去裝wsl啦

# PRESENTING CODE

去他們的官方網站下載後照著教學

手動編譯安裝

怎麼用

Use C++ Boost Library

引入

#include <boost/whatever.hpp>
# PRESENTING CODE
# PRESENTING CODE

使用 - 以智能指標為例

#include<iostream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

using namespace std;


// 定義一個類別
class MyClass {
public:
    MyClass(int data) : mData(data) {}
    void printData() {
        cout << "Data: " << mData << endl;
    }
private:
    int mData;
};

int main() {
	boost::shared_ptr<MyClass> ptr1 = boost::make_shared<MyClass>(42);
}

智能指標

Smart Pointers

Why smart pointers?

# PRESENTING CODE
  • 自動記憶體管理
  • 自動計數 (Reference Counting)
  • 避免野指針 (Dangling Pointers)
  • 方便
  • 喔對 C++ 11 以後就自帶這東西了

shared_ptr

# PRESENTING CODE
  • 功能shared_ptr 是一種共享所有權的智能指標,可以跟蹤對象的引用計數,當引用計數為零時自動釋放記憶體。

  •  

  • 使用情境:當需要多個指標共享同一個對象時,使用 shared_ptr 是很合適的。例如,在多個函式之間傳遞一個對象,或者將對象存儲在容器中。

shared_ptr

# PRESENTING CODE
#include <memory>
#include <iostream>

using namespace std;

int main() {
   	shared_ptr<int> ptr1 = make_shared<int>(42);
    shared_ptr<int> ptr2 = ptr1; // 共享 ptr1 的資源

    cout << *ptr1 << endl; // 輸出 42
    cout << *ptr2 << endl; // 輸出 42

    return 0;
}
# PRESENTING CODE

weak_ptr

# PRESENTING CODE
  • 功能weak_ptr 是一種弱引用的智能指標,它不會增加對象的引用計數,不會阻止對象的釋放,通常與 shared_ptr 搭配使用,用於解決循環引用的問題。

  •  

  • 使用情境:當需要避免循環引用時,通常將 weak_ptr 用於解決此問題。例如,當兩個對象彼此擁有 shared_ptr 指向對方時,可能會形成循環引用。

# PRESENTING CODE
# PRESENTING CODE

weak_ptr

#include <memory>
#include <iostream>

using namespace std;

int main() {
    shared_ptr<int> sharedPtr = make_shared<int>(42);
    weak_ptr<int> weakPtr = sharedPtr;
    
    // 使用 lock() 方法獲取強引用
    if (auto shared = weakPtr.lock()) {
        cout << "Weak pointer is valid." << endl;
        cout << "Value: " << *shared << endl;
    } else {
        cout << "Weak pointer is expired." << endl;
    }
    
    return 0;
}

unique_ptr

# PRESENTING CODE
  • 功能unique_ptr 是一種獨占所有權的智能指標,表示只有一個指標可以擁有對象,當該指標超出作用域時,對象會被自動釋放。

  •  

  • 使用情境:當需要確保只有一個指標可以擁有對象時,使用 unique_ptr 是合適的。例如,在動態分配記憶體後需要確保釋放。

unique_ptr

# PRESENTING CODE
#include <memory>
#include <iostream>

using namespace std;

int main() {
    unique_ptr<int> ptr1(new int(42));
    unique_ptr<int> ptr2 = ptr1; // 無法複製

    cout << *ptr1 << endl; // 輸出 42

    return 0;
}

演算法

Algorithms

  字串

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
# PRESENTING CODE

  字串 - 排序

​    以字母順序排序字串

#include <bits/stdc++.h>
#include <boost/algorithm/string.hpp>

using namespace std;

int main() {
    vector<string> strings = {"apple", "banana", "cherry", "banana", "apple"};
    
    boost::algorithm::sort(strings);
    
	for (const auto& str : strings) {
        cout << str << endl; // apple apple banana banana cherry
    }
}
# PRESENTING CODE

  字串 - 處理重複字串​

#include <bits/stdc++.h>
#include <boost/algorithm/string.hpp>

using namespace std;

int main() {
    vector<string> strings = {"apple", "apple", "apple", "banana", "apple"};
    
    auto it = boost::algorithm::unique(strings);
    strings.erase(it, strings.end());

    
	for (const auto& str : strings) {
        cout << str << endl; // apple banana
    }
}
# PRESENTING CODE

  圖 - DFS

#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>

using namespace std;

// 定義一個 Graph 類型
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;

// 定義一個訪問者類型
struct MyVisitor : boost::default_dfs_visitor {
    template <typename Vertex, typename Graph>
    void discover_vertex(Vertex v, const Graph& g) const {
        cout << "Discovered vertex: " << v << endl;
    }
};

int main() {
    // 創建一個 Graph 對象
    Graph g;

    // 添加一些節點和邊
    boost::add_edge(0, 1, g);
    boost::add_edge(0, 2, g);
    boost::add_edge(1, 3, g);
    boost::add_edge(2, 4, g);
    boost::add_edge(3, 4, g);

    // 執行深度優先搜索
    boost::depth_first_search(g, boost::visitor(MyVisitor()));

    return 0;
}
# PRESENTING CODE

  圖 - BFS

#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/breadth_first_search.hpp>

using namespace std;

// 定義一個 Graph 類型
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;

// 定義一個訪問者類型
struct MyVisitor : boost::default_bfs_visitor {
    template <typename Vertex, typename Graph>
    void discover_vertex(Vertex v, const Graph& g) const {
        cout << "Discovered vertex: " << v << endl;
    }
};

int main() {
    // 創建一個 Graph 對象
    Graph g;

    // 添加一些節點和邊
    boost::add_edge(0, 1, g);
    boost::add_edge(0, 2, g);
    boost::add_edge(1, 3, g);
    boost::add_edge(2, 4, g);
    boost::add_edge(3, 4, g);

    // 執行廣度優先搜索
    boost::breadth_first_search(g, 0, boost::visitor(MyVisitor()));

    return 0;
}
# PRESENTING CODE

正規表達式

Regular Expression (Regex)

  正規表達式 - 引入

#include <iostream>
#include <string>
#include <boost/regex.hpp>
# PRESENTING CODE

  正規表達式 - 🌰

#include <bits/stdc++.h>
#include <boost/regex.hpp>

using namespace std;

int main() {
    // 待匹配的字串
    tring text = "Emails: user1@example.com, user2@example.com, user3@example.com";
    
    // 正則表達式
    boost::regex regex_pattern("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}");
    
    // 匹配結果對象
    boost::smatch match_result;
    
    // 遍歷字串,匹配並輸出結果
    while (boost::regex_search(text, match_result, regex_pattern)) {
        cout << "Found email: " << match_result[0] << endl;
        text = match_result.suffix().str(); // 更新待匹配的字串
    }
    
    return 0;
}
# PRESENTING CODE

多線程

Thread (不是Threads那個app)

  多線程 - 引入

#include <iostream>
#include <boost/thread.hpp>
# PRESENTING CODE

  多線程 - 🌰

#include <iostream>
#include <boost/thread.hpp>

using namespace std;

// 定義一個簡單的函式,用於輸出一系列數字
void printNumbers(int start, int end) {
    for (int i = start; i <= end; ++i) {
        cout << i << " ";
    }
    cout << endl;
}

int main() {
    // 創建兩個線程,分別執行不同的任務
    boost::thread thread1(printNumbers, 1, 5);
    boost::thread thread2(printNumbers, 6, 10);

    // 等待兩個線程完成
    thread1.join();
    thread2.join();

    return 0;
}
# PRESENTING CODE

數學

MATH =  Mental Abuse To Human

  數學?

# PRESENTING CODE
  • 數學常數 ex: pi

  • 特殊函數 ex: sin cos tan

  • 統計函數 ex: 取標準差

  數學 - 引入

# PRESENTING CODE
#include <iostream>
#include <boost/math/whatever/whatever.hpp>

  數學 - 數學常數

# PRESENTING CODE
#include <iostream>
#include <boost/math/constants/constants.hpp>

using namespace std;

int main() {

    double pi = boost::math::constants::pi<double>();

    cout << "圓周率 π 的值是:" << pi << endl;

    return 0;
}

  數學 - 特殊函式

# PRESENTING CODE
#include <iostream>
#include <boost/math/special_functions.hpp>

using namespace std;

int main() {
    double angle = 0.5;

    double sine_value = boost::math::sin(angle);
    double cosine_value = boost::math::cos(angle);
    double tangent_value = boost::math::tan(angle);

    cout << "角度 " << angle << " 的正弦值是:" << sine_value << endl;
    cout << "角度 " << angle << " 的餘弦值是:" << cosine_value << endl;
    cout << "角度 " << angle << " 的正切值是:" << tangent_value << endl;

    return 0;
}

  數學 - 特殊函式

# PRESENTING CODE
#include <bits/stdc++.h>
#include <boost/math/statistics/univariate_statistics.hpp>

using namespace std;

int main() {
    // 定義一個數組
   	vector<double> data = {1.2, 2.5, 3.8, 4.6, 5.7};

    // 計算數組的標準差
    double stddev = boost::math::statistics::standard_deviation(data.begin(), data.end());

    cout << "數組的標準差是:" << stddev << endl;

    return 0;
}

總結

C++ Boost Library很好用

做專案時可以作為良好的輔助

資源

C++ Boost Library 遠不止這些功能,更多功能可以去

這裡找到英文資源

Code

By wen Ian

Code

  • 297