385 字
2 分钟
C++ STL 常用容器速查
什么是 STL?
STL(Standard Template Library)是 C++ 标准模板库,提供了丰富的数据结构和算法。
在信息学竞赛中,熟练使用 STL 可以大幅提高编码效率。
常用容器
1. vector —— 动态数组
#include <vector>using namespace std;
vector<int> v; // 声明v.push_back(1); // 尾部插入v.pop_back(); // 尾部删除v.size(); // 元素个数v[0]; // 随机访问v.clear(); // 清空
// 遍历for (int x : v) { cout << x << " ";}2. map —— 有序映射
#include <map>using namespace std;
map<string, int> mp;mp["hello"] = 1; // 插入/修改mp.count("hello"); // 查询是否存在mp.erase("hello"); // 删除
// 遍历for (auto& [key, val] : mp) { cout << key << ": " << val << endl;}3. set —— 有序集合
#include <set>using namespace std;
set<int> s;s.insert(3); // 插入s.erase(3); // 删除s.count(3); // 是否存在(0 或 1)s.lower_bound(3); // >= 3 的第一个元素4. queue —— 队列(BFS 必备)
#include <queue>using namespace std;
queue<int> q;q.push(1); // 入队q.front(); // 队首q.pop(); // 出队q.empty(); // 是否为空5. priority_queue —— 优先队列
#include <queue>using namespace std;
// 大根堆(默认)priority_queue<int> pq;
// 小根堆priority_queue<int, vector<int>, greater<int>> pq_min;
pq.push(3);pq.top(); // 堆顶pq.pop(); // 弹出堆顶6. stack —— 栈
#include <stack>using namespace std;
stack<int> st;st.push(1); // 入栈st.top(); // 栈顶st.pop(); // 出栈速查表
| 容器 | 头文件 | 插入 | 查询 | 删除 | 特点 |
|---|---|---|---|---|---|
vector | <vector> | 均摊 | 动态数组 | ||
map | <map> | 有序键值对 | |||
unordered_map | <unordered_map> | 均摊 | 均摊 | 均摊 | 哈希映射 |
set | <set> | 有序集合 | |||
queue | <queue> | FIFO | |||
stack | <stack> | LIFO | |||
priority_queue | <queue> | 堆 |
TIP竞赛中如果不需要有序性,优先使用
unordered_map和unordered_set,时间复杂度更优。
C++ STL 常用容器速查
https://blog.singlelyra.top/posts/teaching-cpp-stl/