使用動態數組作為底層存儲,支援任意類型元素。核心字段:
T* _array:元素數組指針size_t _capacity:當前分配容量int _topIndex:棧頂索引(-1 表示空) -1) {
cout << _array[_topIndex] << endl;
--_topIndex;
}
}
bool empty() const { return _topIndex == -1; }
};
| 技術點 | 實現細節 |
|---|---|
| 動態擴容策略 | _capacity = 2 * _capacity + 3,均攤 O(1) |
| 深拷貝 vs 淺拷貝 | POD 類型可 memcpy;通用模板必須逐元素拷貝構造 |
| 異常安全 | 先分配新空間、拷貝成功後再釋放舊空間,防止內存洩漏 |
| 析構函數 | 釋放數組內存,避免洩漏 |
s;
s.Push(1); s.Push(2); s.Push(3); s.Push(4);
s.Pop(); // 4
s.Pop(); // 3
s.Pop(); // 2
s.Pop(); // 1
}
int main() { test1(); return 0; }
Top()、Size()、Clear() 等常用接口。std::initializer_list 構造。std::vector 作為底層容器的實現(更簡潔、安全)。