标题
增加 1 行删除 1 行
1废话文学1STL笔记
正文
增加 415 行删除 1 行
1~~### 只有当你逼自己一把时,才会发现自己有多没用~~123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415### pair 数对将两个不同类型的数据绑定在一起,非常适合存储坐标、状态或带权图的边。```pair<int, int> a;int main(){a = {3, 5};cout << a.first << ' ' << a.second; // 输出 3 5return 0;}pair<int, int> a(3, 5);int main(){cout << a.first << ' ' << a.second;return 0;}pair<int, int> a{4, 6};int main(){cout << a.first << ' ' << a.second;return 0;}a = make_pair(4, 6);a.second = 7;//双关键字比较(默认支持,可以直接用 <, == 等):// a < b 的等价逻辑:// a.first < b.first || (a.first == b.first && a.second < b.second)pair 数组/vector 排序:默认按 first 升序,first 相同按 second 升序,可直接 sort。cpppair<int, string> stu;// 三元组:pair 嵌套pair<int, pair<int, int>> b(1, pair<int, int>(2, 3));pair<int, pair<int, int>> b = {1, {2, 3}};cout << b.first << ' ' << b.second.first << ' ' << b.second.second;// C++11 起也可以用 tuple 实现三元组(更推荐)#include <tuple>tuple<int, int, int> t = {1, 2, 3};cout << get<0>(t) << ' ' << get<1>(t) << ' ' << get<2>(t);```### stack 栈LIFO(后进先出)。```#include <stack>stack<int> s;s.push(1); // 压栈 O(1)s.pop(); // 弹栈 O(1),注意:空栈调用 pop 会未定义行为s.top(); // 获取栈顶元素 O(1)s.size(); // 返回 size_t(无符号)s.empty(); // 判空// size() 返回无符号整数,输出时可强转成 intprintf("%d", (int)s.size());// 注意:stack 没有 clear(),清空只能循环 popwhile (!s.empty()) {s.pop();}// 或者直接赋值空栈:s = stack<int>();```### queue 队列FIFO(先进先出)。```#include <queue>queue<int> q;q.push(1); // 队尾入队 O(1)q.pop(); // 队首出队 O(1),空队列调用 pop 会未定义行为q.front(); // 获取队首元素q.back(); // 获取队尾元素q.size();q.empty();// queue 也没有 clear()while (!q.empty()) q.pop();```### priority_queue 优先队列(堆)常用于 Dijkstra 优化、贪心算法。```#include <queue>// 默认是大根堆(从大到小出队)priority_queue<int> q;q.push(1);q.push(3);q.push(2);cout << q.top(); // 输出 3q.pop();// 声明小根堆的固定格式(从小到大出队)priority_queue<int, vector<int>, greater<int>> min_q;// 自定义类型需要提供比较函数(仿函数)struct Node {int dist, id;};struct cmp {bool operator()(Node a, Node b) {return a.dist > b.dist; // 注意:> 表示小根堆}};priority_queue<Node, vector<Node>, cmp> pq;操作复杂度://push() / pop():时间复杂度O(log n)//top():时间复杂度O(1)```### deque 双端队列支持两端 O(1) 插入删除,且支持 O(1) 随机访问。常数较大,非必要少用,常用于单调队列。```#include <deque>deque<int> dq;dq.push_front(1); // 队头插入 O(1)dq.push_back(2); // 队尾插入 O(1)dq.pop_front(); // 队头删除 O(1)dq.pop_back(); // 队尾删除 O(1)dq.size();dq.empty();dq.front(); // 获取队头dq.back(); // 获取队尾cout << dq[1]; // 支持下标随机访问 O(1)```### vector 变长数组```#include <vector>vector<int> v;vector<int> a(3, 100); // 长度为 3,初始值均为 100vector<int> b = {1, 2, 3, 4, 5};vector<int> c(5); // 长度为 5,默认值为 0(基本类型)或默认构造v.push_back(10); // 末尾插入 O(1)(均摊)v.pop_back(); // 删除末尾 O(1)v.clear(); // 清空元素,但【不释放内存】,容量 capacity 不变v.resize(100); // 重新调整大小,新增元素默认值填充v.reserve(1000); // 预分配容量,避免多次扩容// size 宏定义推荐写法,加括号防止运算符优先级问题#define SZ(x) (int)(x).size()```迭代器与遍历```// v.begin() 指向第一个元素,v.end() 指向最后一个元素的【下一个位置】(左闭右开区间)vector<int>::iterator it = v.begin();it++;// 方式1:迭代器遍历for (auto it = v.begin(); it != v.end(); it++) {printf("%d ", *it);}// 方式2:C++11 范围 for 循环(最推荐)for (int x : v) {x += 1; // 仅仅是修改拷贝,不改变原数组}for (int &x : v) {x += 1; // 加引用直接修改原数组}for (const int &x : v) {cout << x; // 只读引用,避免拷贝开销}```常用技巧```sort(v.begin(), v.end()); // 排序 O(n log n)sort(v.begin(), v.end(), greater<int>()); // 降序v.insert(v.begin() + 1, 2); // 在第二个位置插入 2,O(n) 慎用v.erase(v.begin() + 1); // 删除第二个元素,O(n) 慎用v.erase(v.begin(), v.begin() + 3); // 删除前 3 个元素,O(n)// 去重(先排序再 unique)sort(v.begin(), v.end());v.erase(unique(v.begin(), v.end()), v.end());// unique 将重复元素移到末尾,返回新末尾迭代器```存图:邻接表比链式前向星更易写,常数稍大。```vector<int> g[5050];for (int i = 1; i <= n; i++) {int u, v;cin >> u >> v;g[u].push_back(v);g[v].push_back(u);}for (int next_node : g[u]) {// ...}```### set 有序集合内部是红黑树(平衡二叉搜索树)。元素从小到大有序,且自动去重。```#include <set>set<int> s;for (int i = 1; i <= n; i++) {int x;cin >> x;s.insert(x); // 插入 O(log n)}s.erase(x); // 删除值为 x 的元素 O(log n)s.erase(s.begin()); // 删除迭代器指向的元素 O(log n)(均摊)s.erase(s.begin(), s.end()); // 删除区间,等价于 clear()// 遍历for (auto it = s.begin(); it != s.end(); it++) {cout << *it << ' ';}// 查找auto it = s.find(3); // 不存在返回 s.end()if (it == s.end())cout << "no";elsecout << "yes";// 二分查找auto it = s.lower_bound(100); // 第一个 >= 100 的元素auto it = s.upper_bound(100); // 第一个 > 100 的元素if (it != s.end()) cout << *it;// 获取前一个元素auto it2 = prev(it); // 需要头文件 <iterator>,it 前移一位// 或者:auto it2 = it;if (it2 == s.begin()) {// 不存在前一个} else {--it2;}```set 取代堆```s.insert(x);cout << *prev(s.end()); // 输出最大值s.erase(prev(s.end())); // 删除最大值multiset(允许重复元素)cppmultiset<int> ms;ms.insert(1);ms.insert(1); // 允许重复ms.erase(1); // 删除所有值为 1 的元素ms.erase(ms.find(1)); // 只删除一个值为 1 的元素```如果要存重复元素且需要唯一标识,可以用:```set<pair<int, int>> s;s.insert({a[i], i}); // 用下标区分相同值```### map内部同样是红黑树。Key 作为键(必须支持 < 比较),Value 作为值。按照键从小到大排序。```#include <map>map<T1, T2> mp;map<string, string> mp;mp["abc"] = "def";mp["bcd"] = "xyz";// 遍历for (auto x : mp) {cout << x.first << ' ' << x.second << '\n';}// C++17 结构化绑定for (auto [key, val] : mp) {cout << key << ' ' << val;}核心避坑cpp// ❌ 错误做法:if (mp[key] == 1) { ... }// 如果 key 不存在,mp[key] 会自动创建一个默认值(0)插入 map 中,导致内存和常数剧增!// ✅ 正确做法 1:使用 countif (mp.count("abc")) {cout << "存在";}// ✅ 正确做法 2:使用 findif (mp.find("abc") != mp.end()) {cout << mp["abc"];}// ✅ 正确做法 3(C++20):containsif (mp.contains("abc")) { ... }```其他操作```mp.erase("abc"); // 删除指定 key,不存在也安全(返回 0)// 注意:erase 删除不存在的 key 是安全的,不会 REauto it = mp.find("def"); // 找不到返回 mp.end()if (it != mp.end()) {cout << it->first << ' ' << it->second;}// map 的迭代器是 pairauto it = mp.begin();printf("%s %s", it->first.c_str(), it->second.c_str());unordered_set / unordered_map(C++11)底层是哈希表,无序,查找 O(1)(平均)。``````#include <unordered_set>#include <unordered_map>unordered_set<int> us;us.insert(3);if (us.find(3) != us.end()) { ... }unordered_map<string, int> um;um["apple"] = 5;if (um.count("apple")) { ... }//注意:自定义类型作为 Key 时,需要提供哈希函数。```### 算法类 STL(<algorithm>)sort 排序```#include <algorithm>sort(v.begin(), v.end()); // 默认升序sort(v.begin(), v.end(), greater<int>()); // 降序sort(a, a + n); // 数组排序// 自定义比较函数sort(v.begin(), v.end(), [](int a, int b) {return a > b; // 降序});// 结构体排序struct Node { int x, y; };sort(nodes.begin(), nodes.end(), [](Node a, Node b) {if (a.x != b.x) return a.x < b.x;return a.y < b.y;});lower_bound / upper_bound(二分查找)要求序列有序。cpp// vectorauto it = lower_bound(v.begin(), v.end(), x); // 第一个 >= x 的位置auto it = upper_bound(v.begin(), v.end(), x); // 第一个 > x 的位置if (it != v.end()) cout << *it;// 数组int* p = lower_bound(a, a + n, x);int pos = lower_bound(a, a + n, x) - a; // 下标// 自定义比较(如降序)sort(v.begin(), v.end(), greater<int>());auto it = lower_bound(v.begin(), v.end(), x, greater<int>());binary_search(判断是否存在)cppbool exists = binary_search(v.begin(), v.end(), x); // O(log n)max / min / swapcppint mx = max(a, b);int mn = min(a, b);swap(a, b); // 交换 O(1)// 多个元素取最值(C++11)int mx = max({1, 2, 3, 4, 5});reverse 反转cppreverse(v.begin(), v.end()); // 反转整个 vectorreverse(a, a + n); // 反转数组fill 填充cppfill(v.begin(), v.end(), 0); // 将 vector 全部赋值为 0fill(a, a + n, -1); // 数组全部赋值为 -1max_element / min_element(求最值迭代器)cppauto it = max_element(v.begin(), v.end());cout << *it; // 最大值cout << max_element(v.begin(), v.end()) - v.begin(); // 最大值下标auto it = min_element(v.begin(), v.end());accumulate 求和(<numeric>)cpp#include <numeric>int sum = accumulate(v.begin(), v.end(), 0); // 初始值为 0long long sum = accumulate(v.begin(), v.end(), 0LL);next_permutation 全排列cppvector<int> v = {1, 2, 3};do {for (int x : v) cout << x << ' ';cout << '\n';} while (next_permutation(v.begin(), v.end()));// 输出 1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2, 3 2 1// 注意:需要序列有序(升序)才能输出所有排列```容器选择指南需要频繁随机访问,主要在尾部操作 vector需要在头尾两端频繁操作 deque需要在中间频繁插入/删除 list需要键值对映射,且需要有序遍历 map需要键值对映射,只关心快速查找,不关心顺序 unordered_map需要去重且有序的元素集合 set只需要去重,不关心顺序 unordered_set后进先出(LIFO) stack先进先出(FIFO) queue需要动态获取最大/最小元素 priority_queue需要存储二元组/三元组 pair / tuple