第20章 - 容器类
嗨,朋友!我是长安。
STL提供了多种容器,每种都有特定的用途。这一章学习常用的容器:list、deque、stack、queue。
📜 List - 双向链表
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> myList;
// 添加元素
myList.push_back(10); // 尾部添加
myList.push_front(5); // 头部添加
myList.push_back(20);
// 遍历
cout << "链表内容:";
for (int val : myList) {
cout << val << " ";
}
cout << endl;
// 插入
auto it = myList.begin();
advance(it, 1); // 移动到第2个位置
myList.insert(it, 15);
// 删除
myList.remove(10); // 删除值为10的元素
// 大小
cout << "大小:" << myList.size() << endl;
return 0;
}
输出:
链表内容:5 10 20
大小:3
🎯 Deque - 双端队列
#include <iostream>
#include <deque>
using namespace std;
int main() {
deque<int> dq;
// 两端添加
dq.push_back(20);
dq.push_front(10);
dq.push_back(30);
dq.push_front(5);
// 访问
cout << "首元素:" << dq.front() << endl;
cout << "尾元素:" << dq.back() << endl;
// 遍历
cout << "内容:";
for (int val : dq) {
cout << val << " ";
}
cout << endl;
// 两端删除
dq.pop_front();
dq.pop_back();
return 0;
}
输出:
首元素:5
尾元素:30
内容:5 10 20 30
📚 Stack - 栈(LIFO)
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> s;
// 压栈
s.push(10);
s.push(20);
s.push(30);
cout << "栈的大小:" << s.size() << endl;
// 出栈
while (!s.empty()) {
cout << "栈顶:" << s.top() << endl;
s.pop();
}
return 0;
}
输出:
栈的大小:3
栈顶:30
栈顶:20
栈顶:10
🎫 Queue - 队列(FIFO)
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<string> q;
// 入队
q.push("张三");
q.push("李四");
q.push("王五");
cout << "队列大小:" << q.size() << endl;
// 出队
while (!q.empty()) {
cout << "队首:" << q.front() << endl;
q.pop();
}
return 0;
}
输出:
队列大小:3
队首:张三
队首:李四
队首:王五
🔥 Priority Queue - 优先队列
#include <iostream>
#include <queue>
using namespace std;
int main() {
priority_queue<int> pq;
// 添加元素
pq.push(30);
pq.push(10);
pq.push(50);
pq.push(20);
// 自动按优先级排序(默认大顶堆)
while (!pq.empty()) {
cout << pq.top() << " ";
pq.pop();
}
cout << endl;
return 0;
}
输出:
50 30 20 10
🌟 实战案例:表达式求值
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int calculate(int a, int b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
return 0;
}
int evaluatePostfix(string expr) {
stack<int> s;
for (char c : expr) {
if (isdigit(c)) {
s.push(c - '0');
} else if (isOperator(c)) {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
s.push(calculate(a, b, c));
}
}
return s.top();
}
int main() {
string postfix = "23*54*+"; // (2*3) + (5*4) = 26
cout << "后缀表达式:" << postfix << endl;
cout << "结果:" << evaluatePostfix(postfix) << endl;
return 0;
}
🎯 容器选择指南
| 需求 | 推荐容器 |
|---|---|
| 频繁随机访问 | vector, deque |
| 频繁插入/删除(中间) | list |
| 两端操作 | deque |
| LIFO(后进先出) | stack |
| FIFO(先进先出) | queue |
| 优先级处理 | priority_queue |
