寫數據結構代碼時,目標是「算法正確、封裝優秀」。建議採用**三階段漸進式重構**:
此法將「邏輯設計」與「接口設計」解耦,避免過早優化導致反覆修改。
// 環形緩衝區,空出一格區分滿/空
#define MAX 100
int buf[MAX];
int head = 0, tail = 0;
bool push(int x) {
if ((tail + 1) % MAX == head) return false; // 滿
buf[tail] = x;
tail = (tail + 1) % MAX;
return true;
}
bool pop(int &x) {
if (head == tail) return false; // 空
x = buf[head];
head = (head + 1) % MAX;
return true;
}
// 測試代碼混在主函數或 #ifdef TEST 區塊
// BoundedQueue.h
class BoundedQueue {
int *buf; int cap, head, tail;
public:
BoundedQueue(int capacity) : cap(capacity+1), head(0), tail(0) {
buf = new int[cap];
}
~BoundedQueue() { delete[] buf; }
bool push(int x) {
if ((tail+1)%cap == head) return false;
buf[tail] = x; tail = (tail+1)%cap; return true;
}
bool pop(int &x) {
if (head == tail) return false;
x = buf[head]; head = (head+1)%cap; return true;
}
bool empty() const { return head == tail; }
bool full() const { return (tail+1)%cap == head; }
};
測試代碼獨立編譯,驗證類行為。
// BoundedQueue.h
template <typename T, int CAPACITY>
class BoundedQueue {
T buf[CAPACITY+1];
int head, tail;
public:
BoundedQueue() : head(0), tail(0) {}
bool push(const T &x) {
if ((tail+1)%(CAPACITY+1) == head) return false;
buf[tail] = x; tail = (tail+1)%(CAPACITY+1); return true;
}
bool pop(T &x) {
if (head == tail) return false;
x = buf[head]; head = (head+1)%(CAPACITY+1); return true;
}
bool empty() const { return head == tail; }
bool full() const { return (tail+1)%(CAPACITY+1) == head; }
};
現在可支援任意類型、編譯期固定容量:BoundedQueue<int, 100> q;。
若需運行期決定容量,可改用 `T* buf` + 建構函數傳入 size。
test.cpp,include header。| 階段 | 關注點 | 優勢 |
|---|---|---|
| C | 純算法邏輯 | 快速驗證正確性,無封裝干擾 |
| Class | 接口設計、封裝 | 隱藏細節,資源管理(RAII),易維護 |
| Template | 泛型復用 | 類型安全,零開銷抽象,最大復用 |
this-> 或 Base<T>::)。「C → Class → Template」三步走,不只是代碼重構,更是**思維模式的升級**:從關注「怎麼算」到「怎麼用」再到「怎麼通用」。這條路徑讓數據結構教材上的 C 代碼真正轉化為工業級 C++ 組件庫的基石。