STL总结
YWJ20140130
·
·
算法·理论
STL总结
这是一个新的开始。以后的总结会更偏向Q&A和例题,而不再赘述一些成员函数。
这里不是技术文档。
例如:
Q:为什么要写总结?
A:总结不仅是一段学习的汇总,也是你与他人复习的工具。
Q:我的代码为什么会\color{red}\tt{WA}?
int main(){
short a,b;
cin>>a>>b;
cout<<a+b;
}
A:没有使用int。short会溢出。
- 类
- 函数
- 迭代器
### 先从类讲起。
---
#### `vector`-动态数组/向量
##### Q&A
Q:`vector`是怎么存储的?
A:`vector`会**扩被存储**。具体见下:
|元素个数|实际大小|
|:--:|:--:|
| $$ 0 | 0 |
| $$1 | 1 |
| $$2 | 2 |
| 3 | 2 |
| $$4 | 4 |
| 5 | 4 |
| 6 | 4 |
| 7 | 4 |
| $$8 | 8 |
| 9 | 8 |
$\hspace{.7cm}$**如果访问未被开辟的内存,会$\color{purple}\tt{RE}$**。
$\hspace{.7cm}$当然也有卡`vector`的,比如 $2^k+1$ 一类的数据,`vector`会再开一倍空间,**甚至**$\color{#110066}\tt{MLE}$。
Q:为什么我的代码会$\color{purple}\tt{RE}$?
```cpp
vector<int> v;
int n;
int main(){
cin>>n;
for(int i=1;i<=n;i++) cin>>v[i];
}
```
A:不能直接输入`vector`的每一项,不然会溢出,详细见上。
$\hspace{.7cm}$如何避免呢?只需要在循环前插入一句`v.resize(n);`即可。
$\hspace{.7cm}$`resize`用于设置`vector`大小,这样就不会$\color{purple}\tt{RE}$了。
$\hspace{.7cm}$或者使用`push_back`方法。
---
##### 例题
`vector`没有特定例题,它更像另一种数组。
所以不赘述例题。
---
#### `set`-集合
##### Q&A
Q:为什么我的代码会$\color{#cccc00}\tt{CE}$?
```cpp
set<int> st;
int n;
int main(){
cin>>n;
for(int i=1;i<=n;i++){
int x;
cin>>x;
st.push_back(x);
}
}
```
A:`set`不使用`push_back`加入元素,而是使用`insert`方法。
Q:为什么我的代码会$\color{red}\tt{WA}$?
> 给定 $n$ 和 $n$ 个数的序列 $a_1\sim a_n$,将 $a$ 去重后按输入顺序输出。
```cpp
set<int> st;
int n;
int main(){
cin>>n;
for(int i=1;i<=n;i++){
int x;
cin>>x;
st.insert(x);
}
for(auto p:st) cout<<p<<' ';
}
```
A:`set`会自动排序元素,所以 $a$ 会被打乱顺序。使用`unordered_set`可以不排序元素,但代价是查询时间略短。
---
##### 例题
**eg.1.** [\[NOIP 2006 普及组\] 明明的随机数](https://www.luogu.com.cn/problem/P1059)
这道题又让去重又让排序,属实是把`set`喂嘴里了。
代码:
```cpp
int n;
set<int> s;
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
s.insert(x);
}
cout << s.size() << "\n";
for (auto p : s) cout << p << ' ';
}
```
---
#### `map`-键值对/映射
##### Q&A
Q:迭代器循环`map`时,`auto`的类型是什么?
A:考虑以下代码:
```cpp
map<type1,type2> mp;
for(auto p:mp);
```
$\hspace{.7cm}$此时`auto`的类型是`pair<type1,type2>`
Q:`auto`循环中的`pair`类型、`map`定义时,哪个值是键,哪个是值?
A:第一个类型(同上文`type1`)是键,第二个(同上文`type2`)是值。
Q:`map`会排序/去重吗?
A:第一,会排序。第二,因为它是键对值,所以一键对一值,也有去重效果。
$\hspace{.7cm}$使用`map`去重做[\[NOIP 2006 普及组\] 明明的随机数](https://www.luogu.com.cn/problem/P1059):
```cpp
int n;
map<int,bool> mp;
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
mp[x]=1;
}
cout << mp.size() << "\n";
for (auto p : mp)
if(p.second)
cout<<p.first<<' ';
}
```
Q:为什么我的代码$\color{red}\tt{WA}$了?
>#### 题目描述
>在一个网络系统中有N个用户 $1≤N≤1000$、$M$ 次上网记录 $1≤M≤5000$。每个用户可以自己注册一个用户名,每个用户名是一个只含小写字母的字符串。每个上网的账号每次上网都会浏览网页,网页名是一串只含小写字母的字符串,每次上网日志都会留下记录,现在请你统计一次上网日志中,每个用户浏览了多少个网页。(输出按照输入顺序输出)
>#### 输入格式
>第一行 $N$ 和 $M$ 第 $2$ 行到第 $M+1$ 行为 $M$ 条上网日志,每行两个字符串,用空格隔开
>#### 输出格式
>$N$ 个ID的上网记录,具体看样例。
>#### 样例输入
>```
>5 7
>guomao wangyi
>lifan tengxun
>zhoushijian souhu
>zhangshilin tengxun
>guomao souhu
>zhoushijian wangyi
>liuyang bilibili
>```
>#### 样例输出
>```
>guomao wangyi souhu
>lifan tengxun
>zhoushijian souhu wangyi
>zhangshilin tengxun
>liuyang bilibili
>```
```cpp
#include <bits/stdc++.h>
using namespace std;
int n, m;
map<string, vector<string>> xx;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= m; i++) {
string a, b;
cin >> a >> b;
xx[a].push_back(b);
}
string s;
vector<string> v;
for (auto p : xx) {
s += p.first;
s += ' ';
for (auto pp : p.second) s += (pp + ' ');
v.push_back(s);
s.clear();
}
reverse(v.begin(), v.end());
for (auto p : v) cout << p << "\n";
}
```
A:这段代码不仅没使用`unordered_map`来不排序数据,即使使用了`unordered_map`也会有问题:
$\hspace{.7cm}$`unordered_map`会将**最后更新的键值对提前**,顺序也不对了。
$\hspace{.7cm}$所以,可以使用一个`string`存储输入顺序,最后按输入顺序输出。
$\hspace{.7cm}$正确代码:
```cpp
int n, m;
unordered_map<string, vector<string>> xx;
map<string, bool> x;
string pp[100001];
int main() {
ios::sync_with_stdio(0),cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= m; i++) {
string a, b;
cin >> a >> b;
pp[i] = a;
xx[a].push_back(b);
}
for (int i = 1; i <= m; i++) {
if (x[pp[i]])
continue;
x[pp[i]] = 1;
cout << pp[i] << ' ';
for (auto p : xx[pp[i]]) cout << p << ' ';
cout << "\n";
}
}
```
---
#### `queue`-队列
`queue`一端进,一端出,现进后进。
##### `BFS`的讲解
`queue`常用于`BFS`(广度优先搜索),BFS模板如下:
```cpp
queue<int> lis;
lis.push(起点下标);
vis[起点下标]=1;
while(lis.size()){
int idx=lis.back();
lis.pop();
if(idx==终点) 输出答案;
if(vis[idx]) continue;
if(idx 不和标) continue;
for(i=遍历 idx 临接点)
lis.push(i);
}
```
##### `BFS`的例题
##### eg.1.[躲避蚊子](https://www.luogu.com.cn/problem/T676151)
这道题是很版的BFS。
代码:
```cpp
typedef pair<int, int> PT;
int N, M;
bool p[1001][1001];
char a[1001][1001];
const PT P[4] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
bool BFS(PT start) {
vector<PT> L;
L.push_back(start);
while (L.size()) {
PT l = L.back();
L.pop_back();
int F = l.first, S = l.second;
if (F < 1 || F > N) continue;
if (S < 1 || S > M) continue;
if (p[F][S]) continue;
if (a[F][S] == 'w') continue;
p[F][S] = 1;
if (a[F][S] == 'S') return 1;
for (int i = 0; i < 4; i++)
L.push_back({F + P[i].first,
S + P[i].second
});
}
return 0;
}
int main() {
cin >> N >> M;
PT st;
for (int i = 1; i <= N; i++)
for (int j = 1; j <= M; j++) {
char s;
cin >> s;
if (s == 'Y') st = {i, j};
a[i][j] = s;
}
cout << (BFS(st) ? "SAFE" : "NO");
return 0;
}
```
---
#### `priority_queue`-堆
##### 堆讲解
对于堆的讲解详见[OI-wiki-堆](https://oi-wiki.org/lang/pb-ds/pq/)。
堆是一种自动排序的数据结构,插入时间复杂度为 $Θ(\log n)$,可实现快速实现插入时排序。
`priority_queue`初始从小到大排序,但通过插入**负元素**可以实现从大到小排序。详见下。
##### 堆例题
##### eg.1.[abc458-D - Chalkboard Median](https://atcoder.jp/contests/abc458/tasks/abc458_d)
这道题通过两个`priority_queue`,分别维护比中位数小的部分、比中位数大的部分,时间复杂度 $Θ(Q\log Q)$。
代码:
```cpp
int x,q;
int main(){
cin>>x>>q;
while(q--){
int a,b;
cin>>a>>b;
if(a<x) l.push(a);
else r.push(-a);
if(b<x) l.push(b);
else r.push(-b);
if(a<x&&b<x){
r.push(-x);
x=l.top();
l.pop();
}else if(a>x&&b>x){
l.push(x);
x=-r.top();
r.pop();
}
cout<<x<<"\n";
}
return 0;
}
```
---
#### `list`-链表
- 链表的优点:插入、删除快;
- 缺点:访问、更改慢,无法随机访问。
---
#### `deque`-双端队列
可以**双端**插入、删除的`queue`。
---
#### `stack`-栈
同一端插入/删除,先进后出。
---
#### `pair`-值对
可存储两个值,相当于一个简易的结构体。
```cpp
pair<type1,type2> 变量名; //定义
变量名.first; //第一个值的访问
变量名.second; //第二个值的访问
```
---
#### 其他
$\color{gray}{\tt{ST}}\color{red}{\huge{L}}$还有很多其他的类,但以上都是常用的。
---
### 迭代器-iterator
每个$\color{gray}{\tt{ST}}\color{red}{\huge{L}}$的类都有匹配的迭代器。
#### Q&A
Q:迭代器是指针吗?
A:**迭代器不是指针**,虽然它很想指针。迭代器是一个类。
$\hspace{.7cm}$应区分下标、指针、迭代器。
$\hspace{.7cm}$迭代器也可以认为是$\color{gray}{\tt{ST}}\color{red}{\huge{L}}$的“指针”。
Q:如何使用迭代器遍历容器?
A:两种`for`循环方法:
```cpp
for(auto it=容器.begin();it!=容器.end();it++) 访问元素用*it;
for(auto 变量名:容器);
```
$\hspace{.7cm}$在第一种循环里,`it`的类型是 容器类型名称对应的迭代器,例如:
```cpp
vector<int> v;
for(auto it=v.begin();it!=v.end();it++);
for(auto p:v);
```
$\hspace{.7cm}$此时第一个循环`auto`的类型是`vector<int>::iterator`,
$\hspace{.7cm}$第二个循环是`int`。
---
### 函数
下面是几个常用函数:
| 函数名 | 用途 |
|:--:|:--:|
| `sort(begin,end)` | 排序两个迭代器/指针之间的内容,**并不稳定**。 |
| `sort(begin,end,cmp)` | 排序两个迭代器/指针之间的内容,在未重载运算符/需要自定义排序时提供排序函数,**并不稳定**。 |
| `stable_sort(begin,end)` | 排序两个迭代器/指针之间的内容,但是**稳定排序**。 |
| `stable_sort(begin,end,cmp)` |排序两个迭代器/指针之间的内容,在未重载运算符/需要自定义排序时提供排序函数,但是**稳定排序**。 |
| `reverse(begin,end)` | 反转两个迭代器/指针之间的内容。 |
| `make_pair(first,second)` | 制作一个`pair`,并返回它。(或使用`{first,second}`) |
| `unique(begin,end)` | 将两个迭代器之间的重复元素放在后面,并返回其余元素结尾迭代器。 |
| `unique(begin,end)` | 例如:`1 2 3 1 2 5 3`->`1 2 3 5 1 2 3` |
| `lower_bound(begin,end,val)` | 二分查找两个迭代器之间第一个**大于**`val`的元素,返回它的迭代器。要求元素被排序。|
| `upper_bound(begin,end,val)` | 二分查找两个迭代器之间第一个**大于等于**`val`的元素,返回它的迭代器。要求元素被排序。|
其余相关排序`STL`:[OI-wiki-排序相关 STL](https://oi-wiki.org/basic/stl-sort/)。
#### Q&A
Q:如何去重`vector`?
A:这要用`sort`、`unique`和`vector::erase`。代码如下:
```cpp
vector<int> v;
sort(v.begin(),v.end());
v.erase(unique(v.begin(),v.end()),v.end());
```
Q:如何查找`vector`中有几个`val`?
A:使用二分查找可以做到。具体代码:
```cpp
vector<int> v;
int cnt = upper_bound(v.begin(), v.end(), val) - \
lower_bound(v.begin(), v.end(), val);
```
---
### 总结
$\color{gray}{\tt{ST}}\color{red}{\huge{L}}$可以让代码变短很多很多,是后期的基础,熟练掌握很重要。
---
# 凡是过去,皆为序章。爱所有人,信任少数人,不负任何人。我荒废了时间,时间便把我荒废了。