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>O(1)O(1) 均摊O(1)O(1)O(n)O(n)动态数组
map<map>O(logn)O(\log n)O(logn)O(\log n)O(logn)O(\log n)有序键值对
unordered_map<unordered_map>O(1)O(1) 均摊O(1)O(1) 均摊O(1)O(1) 均摊哈希映射
set<set>O(logn)O(\log n)O(logn)O(\log n)O(logn)O(\log n)有序集合
queue<queue>O(1)O(1)O(1)O(1)O(1)O(1)FIFO
stack<stack>O(1)O(1)O(1)O(1)O(1)O(1)LIFO
priority_queue<queue>O(logn)O(\log n)O(1)O(1)O(logn)O(\log n)
TIP

竞赛中如果不需要有序性,优先使用 unordered_mapunordered_set,时间复杂度更优。

C++ STL 常用容器速查
https://blog.singlelyra.top/posts/teaching-cpp-stl/
作者
ByteCraft
发布于
2026-03-10
许可协议
CC BY-NC-SA 4.0