標準模板庫(STL)是 C++ 泛型程式設計的集大成者,其設計哲學深刻影響了現代 C++ 開發。本文不作入門教學,而是從架構視角剖析 STL 三大核心組件——容器、演算法、迭代器——如何透過抽象化實現極致的複用性。
| 組件 | 代表類別/函式 | 核心職責 |
|---|---|---|
| 容器 | vector, list, deque, map, set... | 管理資料儲存與記憶體配置 |
| 演算法 | sort, find, copy, transform... | 實作資料操作邏輯(排序、搜尋、修改) |
| 迭代器 | iterator, const_iterator, reverse_iterator... | 提供統一介面串聯容器與演算法 |
迭代器是連接容器與演算法的「膠水」。它模擬指標行為(++、*、==、!=),卻不綁定具體容器類型。STL 定義了一套 Concept(概念) 體系,規範迭代器必須滿足的行為:
istream_iterator)ostream_iterator)forward_list)list, map)vector, deque, 陣列指標)演算法依賴 Concept 而非具體類型。例如 sort 要求 Random Access Iterator,因此適用於 vector、deque、C 陣列,但不適用於 list(需改用 list::sort)。
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <iterator> // ostream_iterator
int main() {
const int READ_COUNT = 5;
std::vector<std::string> words;
std::string input;
// 1. 讀取資料存入容器
for (int i = 0; i < READ_COUNT; ++i) {
std::cin >> input;
words.push_back(input);
}
// 2. 演算法處理:排序
std::sort(words.begin(), words.end());
// 3. 演算法輸出:copy + ostream_iterator
std::copy(words.begin(), words.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
此例展示 STL 組件的無縫協作:vector 提供 begin()/end() 回傳迭代器,sort 与 copy 僅認得迭代器介面,ostream_iterator 將輸出流包裝為 Output Iterator。整個流程零耦合、高複用。
std 命名空間,建議显式使用 std:: 前綴,避免 using namespace std; 汙染全域。<vector>、<algorithm>、<string>。《泛型程式設計與 STL》(Generic Programming and the STL),Matthew H. Austern 著,侯捷/黃俊堯 譯。深入剖析 Concept、Traits、Allocator 等進階機制,是邁向 STL 專家的必經之作。