目錄
什么是庫?
C++中庫的兩種形態:靜態庫 和 動態庫
靜態鏈接 vs 動態鏈接(鏈接 ≠ 庫)
🔒 靜態鏈接(Static Linking)
🔗 動態鏈接(Dynamic Linking)
C++標準庫(Standard Library)
標準模板庫 STL(Standard Template Library)
總結 & 結構圖解?
什么是庫?
庫就是一堆 別人寫好的代碼打包好的文件,讓你可以直接調用里面的函數或類,而不需要自己從零寫。
舉個例子:
你要排序一個數組,不必自己寫冒泡排序或快排,只要用庫函數:
#include <algorithm>
std::sort(array, array + n);
你就像用現成的“排序工具”,節省了造輪子的時間。
?
C++中庫的兩種形態:靜態庫 和 動態庫
類型 | 后綴名(Windows) | 被使用時 | 優點 | 缺點 |
---|---|---|---|---|
靜態庫 | .lib | 編譯時嵌入程序 | 無需額外依賴 | 文件體積大、難更新 |
動態庫 | .dll | 程序運行時加載 | 程序更小,可共享更新 | 運行時需要額外文件 |
Linux 下 | .a (靜態).so (動態) |
?
靜態鏈接 vs 動態鏈接(鏈接 ≠ 庫)
鏈接(Linking)是把你的代碼和庫的代碼“拼裝”成一個完整程序的過程。
🔒 靜態鏈接(Static Linking)
-
編譯階段,庫的內容直接復制進你的程序。
-
程序編譯后獨立,無需外部依賴。
-
缺點:程序體積大;庫升級需要重新編譯整個程序。
🔗 動態鏈接(Dynamic Linking)
-
編譯時只記錄“我要用這個庫”
-
運行時才加載
.dll
或.so
文件 -
缺點:程序運行依賴外部庫,缺失會導致運行失敗
?
C++標準庫(Standard Library)
C++ 自帶的“官方工具箱”,包括以下模塊:
模塊 | 功能 |
---|---|
<iostream> | 輸入輸出(cin , cout ) |
<vector> , <list> | 常用容器 |
<algorithm> | 各種算法(排序、查找等) |
<cmath> | 數學函數(sqrt, pow) |
<functional> | 函數對象、回調 |
示例:
#include <iostream>
#include <vector>
#include <algorithm>int main() {std::vector<int> v = {3, 1, 4};std::sort(v.begin(), v.end());for (int x : v) std::cout << x << " ";
}
標準模板庫 STL(Standard Template Library)
STL 是 C++ 標準庫的一個子集,包含這三大核心:
-
容器(Containers):裝數據的
vector
,list
,map
,unordered_map
,set
等 -
算法(Algorithms):對數據操作
sort
,find
,count
,accumulate
等 -
迭代器(Iterators):容器訪問器
它像“指針”,可以遍歷任何容器
示例:
#include <iostream>
#include <vector>
#include <algorithm>int main() {std::vector<int> nums = {5, 2, 9, 1};std::sort(nums.begin(), nums.end()); // 使用算法for (auto it = nums.begin(); it != nums.end(); ++it) {std::cout << *it << " "; // 使用迭代器訪問容器}
}
輸出:1 2 5 9
-
vector
是容器 -
sort
是算法 -
begin()
/end()
是迭代器
? STL 的優勢:
-
模板化設計(泛型編程):適用于任何類型
-
高性能實現:效率極高,工業級別
-
統一接口:所有容器用法一致,降低學習成本
總結 & 結構圖解?
+----------------------+| C++ Standard Lib |+----------------------+/ | \/ | \+--------+ +----------+ +--------+| IO | | STL | | Math |+--------+ +----------+ +--------+|+-----------+-----------+| | |Containers Algorithms Iterators