語法:
template <typename T>
void swap(T& a, T& b) {
T tmp = a; a = b; b = tmp;
}
調用方式:
swap(a, b) —— 編譯器根據實參類型推導 Tswap<int>(a, b) —— 強制類型| 特性 | 函數模板 | 普通函數 |
|---|---|---|
| 隱式類型轉換 | 不允許 | 允許 |
| 優先級 | 較低 | 優先匹配 |
| 完全匹配時 | 優於普通函數 | — |
可用 swap<>(a,b) 強制使用模板。
反彙編可見:__Z6myswapIiEvRT_S1_ (int版)、__Z6myswapIcEvRT_S1_ (char版) —— 編譯器生成了兩個獨立函數。
語法:
template <typename T>
class Array {
T* data;
int size;
public:
Array(int n) : size(n), data(new T[n]) {}
T& operator[](int i) { return data[i]; }
~Array() { delete[] data; }
};
class B : public A<int>template<typename T> void A<T>::func()STL 容器存儲的是值副本,而非引用。存入的類型必須提供:
若類含裸指針,必須實現深拷貝(三大件/五大件)。
| 運算符 | 用途 | 示例 |
|---|---|---|
static_cast | 基本類型轉換、有繼承關係的指針/引用轉換(編譯期檢查) | int i = static_cast<int>(3.14) |
reinterpret_cast | 無關類型指針轉換、整數與指針互轉(危險,僅重新解釋位模式) | int* p = reinterpret_cast<int*>(charPtr) |
dynamic_cast | 多態類型轉換(運行期檢查,需虛函數),失敗返回 nullptr | Derived* d = dynamic_cast<Derived*>(basePtr) |
const_cast | 移除 const/volatile 屬性 | char* p = const_cast<char*>(str.c_str()) |
static_cast,明確意圖且有檢查reinterpret_cast 極少用,僅用於極底層代碼dynamic_cast 僅用於多態層級轉換try {
// 可能拋出異常的代碼
if (error) throw MyException("msg");
} catch (const MyException& e) {
// 處理特定異常
} catch (...) {
// 捕獲所有其他異常
}
throw 'c' 不能被 catch(int) 捕獲)void func() throw(MyException, std::bad_alloc); // 只能拋出列出類型及其子類 void func() throw(); // 不拋出任何異常 // 無聲明 = 可拋出任意異常
違反聲明會調用 unexpected(),默認調用 terminate() 終止程序。
std::exception 基類,what() 返回錯誤信息std::bad_alloc:new 失敗std::out_of_range:越界訪問std::invalid_argument:無效參數
ios (基類)
├── istream (輸入) ← cin
├── ostream (輸出) ← cout, cerr, clog
└── iostream (輸入輸出)
├── ifstream (文件輸入)
├── ofstream (文件輸出)
└── fstream (文件輸入輸出)
| 對象 | 類 | 設備 | C 對應 |
|---|---|---|---|
| cin | istream_withassign | 鍵盤 | stdin |
| cout | ostream_withassign | 屏幕 | stdout |
| cerr | ostream_withassign | 屏幕(無緩衝) | stderr |
| clog | ostream_withassign | 屏幕(有緩衝) | stderr |
兩種等價方式:
// 1. 成員函數
cout.setf(ios::hex); cout.setf(ios::showbase);
cout.width(10); cout.fill('*');
// 2. 操縱符 (需 #include )
cout << hex << showbase << setw(10) << setfill('*');
常用操縱符:dec/hex/oct、fixed/scientific、setprecision(n)、setw(n)、left/right/internal、showpos/showpoint。
ios::in/out/app/ate/trunc/binary 可組合(|)read(char*, size) / write(const char*, size),配合 reinterpret_cast 存取結構體seekg/seekp (輸入/輸出指針),tellg/tellpoperator() 的類,作為算法策略reverse_iterator 適配器| 場景 | 推薦容器 | 理由 |
|---|---|---|
| 隨機訪問、尾部增刪 | vector | 連續內存、緩存友好 |
| 頭尾雙向增刪 | deque | 分段連續、頭尾 O(1) |
| 中間頻繁增刪 | list | 雙向鏈表、迭代器穩定 |
| 鍵值查找、自動排序 | map | 紅黑樹、O(log n) |
| 唯一鍵集合、排序 | set | 紅黑樹、去重 |
| 後進先出 | stack | deque 適配 |
| 先進先出 | queue | deque 適配 |
| 優先級隊列 | priority_queue | 堆實現 |