第十七章涵蓋 tuple、bitset、正則表達式、隨機數、I/O 流格式控制、文件操作等進階標準庫組件。以下按練習編號分類整理關鍵知識點與完整可編譯代碼。
tuple 適合快速構建多返回值結構,但難以重構。TextQuery 類演示了如何用 shared_ptr 管理動態資源,實現文本查詢功能。
// 17.3 TextQuery 核心結構
class TextQuery {
public:
using line_no = vector::size_type;
using QueryResult = tuple>, shared_ptr>>;
TextQuery(ifstream&);
QueryResult query(const string&) const;
private:
shared_ptr> file;
map>> wm;
};
Sales_data 完整實現了複製控制、移動語義、運算符重載、I/O 運算符。findBook 三種版本分別使用 tuple、pair、自定義結構體返回多值,對比了它們的優劣。
// 17.6 結構體版本(推薦:語義清晰)
struct Matches {
vector::size_type store_idx;
vector::const_iterator first, last;
Matches(size_type s, auto f, auto l) : store_idx(s), first(f), last(l) {}
};
bitset 初始化與位操作(set()、flip()、count())。Bit<N> 封裝 bitset,提供 update()、友元函數 text() 計算答對題數、輸出運算符重載。從基本語法錯誤捕獲(17.14)、"ei" 拼寫規則匹配(17.15-17.16)、文件中查找異常單詞(17.17-17.18)、電話號碼驗證與格式化(17.19-17.26)、郵編格式化(17.27)逐步深入。
// 17.20 電話號碼驗證邏輯
bool valid(const smatch& m) {
if (m[1].matched) // 有左括號
return m[3].matched && (!m[4].matched || m[4].str() == " ");
else // 無左括號
return !m[3].matched && m[4].str() == m[6].str();
}
default_random_engine + uniform_int_distribution 生成隨機數(17.28-17.30)。do-while 作用域陷阱。bernoulli_distribution 實現隨機替換加密。unitbuf、boolalpha、showbase、hexfloat、setfill/setw 等格式化控制實戰。getline() 按行/分隔符讀取(17.37-17.38)。fstream 同時讀寫,tellg/seekg/seekp 精確控制文件指針,在每行末尾追加長度統計。tuple 適合臨時聚合,長期維護用結構體;pair 限兩值。regex_error 捕獲語法錯誤,再用 sregex_iterator 逐個匹配檢視上下文。