使用 stack 和 queue 需包含對應頭文件:
#include <stack> #include <queue>
定義示例:
std::stack<int> stk; // 整數棧 std::queue<int> q; // 整數隊列 std::stack<std::string> s2; // 字符串棧
棧是「後進先出」(LIFO)容器適配器,默認底層容器為 deque。
| 成員函數 | 說明 |
|---|---|
empty() | 棧為空返回 true,否則 false |
size() | 返回元素個數 |
top() | 返回棧頂元素引用(不刪除) |
push(val) | 將 val 壓入棧頂 |
pop() | 彈出棧頂元素(不返回值) |
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<double> s;
for (int i = 0; i < 10; ++i) s.push(i * 1.5);
while (!s.empty()) {
cout << s.top() << '\n';
s.pop();
}
cout << "剩餘元素: " << s.size() << endl;
return 0;
}
隊列是「先進先出」(FIFO)容器適配器,默認底層同為 deque。
| 成員函數 | 說明 |
|---|---|
empty() | 隊列為空返回 true |
size() | 返回元素個數 |
front() | 返回隊首元素引用 |
back() | 返回隊尾元素引用 |
push(val) | 在隊尾插入 val |
pop() | 刪除隊首元素(不返回值) |
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<string> q;
q.push("first"); q.push("second"); q.push("third");
while (!q.empty()) {
cout << q.front() << ' '; // 訪問隊首
q.pop();
}
cout << endl;
return 0;
}
定義於 <queue>,元素按優先級出隊(默認大根堆,即最大元素先出)。
template <class T, class Container = vector<T>, class Compare = less<T>> class priority_queue;
T:元素類型(必需)Container:底層容器(默認 vector)Compare:比較函數對象(默認 less<T>,即大者優先)priority_queue<int> pq1; // 大根堆 priority_queue<int, vector<int>, greater<int>> pq2; // 小根堆 priority_queue<pair<int,int>> pq3; // pair 預設按 first 再 second 比較
struct Task {
int id, pri;
Task(int i, int p) : id(i), pri(p) {}
// 重載 operator< 使優先級高者排在前面(大根堆)
bool operator<(const Task& other) const {
return pri < other.pri; // pri 大者優先
}
};
priority_queue<Task> pq;
pq.push(Task(1, 10));
pq.push(Task(2, 5));
while (!pq.empty()) {
cout << pq.top().id << ':' << pq.top().pri << '\n';
pq.pop();
}
除 STL 外,理解棧的底層實現有助於掌握數據結構原理。以下是鏈式棧的核心代碼:
struct Node { int data; Node* next; };
class LinkStack {
Node* top;
public:
LinkStack() : top(nullptr) {}
void push(int x) {
Node* p = new Node{x, top};
top = p;
}
int pop() {
if (!top) throw "Stack empty";
int val = top->data;
Node* tmp = top;
top = top->next;
delete tmp;
return val;
}
bool empty() const { return top == nullptr; }
};
STL stack、queue、priority_queue 封裝了經典數據結構,提供統一、高效、安全的接口。掌握其用法與底層特性,能大幅提升編程效率與代碼質量。