常用STL
wanneng头
#include <bits/stdc++.h>
#include <vector>
size() 返回元素个数
empty() 返回是否为空
clear() 清空
front()/back()
push_back()/pop_back()
begin()/end()
[]
支持比较运算,按字典序
#include <utility>
typedef pair<int, int> PII
pair<int, int>
first, 第一个元素
second, 第二个元素
支持比较运算,以first为第一关键字,以second为第二关键字(字典序)
vector<pair<int, int>>vec;
sort(vec.begin(), vec.end(), cmp1);
bool cmp1(pair<int,int>a,pair<int,int>b)
{
return a.first < b.first;
}
string,字符串
size()/length() 返回字符串长度
empty()
clear()
substr(起始下标,(子串长度)) 返回子串
c_str() 返回字符串所在字符数组的起始地址
// 返回这个string对应的字符数组的头指针
string s = "Hello World!";
printf("%s", s.c_str()); //输出 "Hello World!"
#include <queue>
queue, 队列
size()
empty()
push() 向队尾插入一个元素
front() 返回队头元素
back() 返回队尾元素
pop() 弹出队头元素
q = queue <int> (); //清空队列
#include <queue>
priority_queue, 优先队列,默认是大根堆
size()
empty()
push() 插入一个元素
top() 返回堆顶元素
pop() 弹出堆顶元素
定义成小根堆的方式:priority_queue<int, vector<int>, greater<int>> q;
#include <stack>
stack, 栈
size()
empty()
push() 向栈顶插入一个元素
top() 返回栈顶元素
pop() 弹出栈顶元素
#include <deque>
deque, 双端队列
size()
empty()
clear()
front()/back()
push_back()/pop_back()
push_front()/pop_front()
begin()/end()
[]
set, map, multiset, multimap, 基于平衡二叉树(红黑树),动态维护有序序列
set中元素已经从小到大排好序
size()
empty()
clear()
begin()/end()
++, -- 返回前驱和后继,时间复杂度 O(logn)
set/multiset
insert() 插入一个数
find() 查找一个数
count() 返回某一个数的个数
erase()
(1) 输入是一个数x,删除所有x O(k + logn)
(2) 输入一个迭代器,删除这个迭代器
lower_bound()/upper_bound()
lower_bound(x) 返回大于等于x的最小的数的迭代器
upper_bound(x) 返回大于x的最小的数的迭代器
map/multimap
insert() 插入的数是一个pair
erase() 输入的参数是pair或者迭代器
find()
[] 注意multimap不支持此操作。 时间复杂度是 O(logn)
lower_bound()/upper_bound()
unordered_set, unordered_map, unordered_multiset, unordered_multimap, 哈希表
和上面类似,增删改查的时间复杂度是 O(1)
不支持 lower_bound()/upper_bound(), 迭代器的++,--
排序
- 定义cmp函数
struct stu
{
string name;
int score, id;
}st[N];
int n, k;
bool cmp(stu a, stu b)
{
if (k)
{
if (a.score == b.score) return a.id < b.id;
return a.score < b.score;
}
else
{
if (a.score == b.score) return a.id < b.id;
return a.score > b.score;
}
}
- bool operator
struct stu
{
int score;
string name;
bool operator < (const stu &t) const
{
return score < t.score;
}
} st[N];
最大公约数
#include <algorithm>
__gcd(n,m);//最大公约数
exit(0)调试法
#include <cstring>
next_permutation(全排列)
作用:
将当前排列更改为全排列中的下一个排列。
如果当前排列已经是全排列中的最后一个排列(元素完全从大到小排列),函数返回 false 并将排列更改为全排列中的第一个排列(元素完全从小到大排列);否则,函数返回 true。
// 1 结合 数组
int a[] = {1, 2, 3, 4, 5};
do{
for(int i = 0; i < 5; i ++) cout << a[i] << " ";
cout << endl;
}while(next_permutation(a, a + 5));
// 2结合 vector
vector<int> a = {1, 2, 3, 4, 5};
do{
for(int i = 0; i < a.size(); i ++) cout << a[i] << " ";
cout << endl;
}while(next_permutation(a.begin(), a.end()));
去我的收藏夹吃灰吧