常用C++STL
向量(vector)容器
变长数组,使用倍增的思想。
初始化
vector <int> a; // 普通初始化
vector <int> a(10); // 定义长度
vector <int> a(10, 3); // 将长度为10的vector全部初始化为3
vector <int> a[10] // vector数组,表示定义10个vector
函数
a.size() || a.length // 返回vector内元素的个数
a.empty() // 返回ture或false,判断是否为空
a.clear() // 清空
a.front() || a.back() // 返回第一个/最后一个数
a.push_back() || a.pop_back() // 队尾插入一个数/队尾删除一个数
a.begin() || a.end() // vector的迭代器
遍历
for (int i = 0; i < n; i ++ ) a.push_back(i); // 下标遍历
for (auto i = a.begin(); i != a.end(); i ++ ) cout << *i << ' '; // 迭代器遍历
for (auto x : a) cout << x << ' '; // 范围遍历
比较运算
vector同样可以用来进行比较运算,比较的方式是通过字典序进行比较。
pair二元组
pair <type, type> p;
pair的取得方式,第一个元素为 p.frist(),第二个为p.second()
pair同样也支持比较运算,以frist为第一关键字,second为第二关键字,进行字典序比较。
初始化
p = make_pair(10, "abc");
p = {20, "abc"};
若要用pair存储两个以上的元素,也可以这样定义
pair<int, pair<int, int>> p;
字符串string
初始化
string a = "abc";
a += "bcd"; // string可以在字符串后加上一个字符串或字符。
函数
a.size(); // 长度
a.empty(); // 判断空
a.clear(); // 清空
a.substr(x, y); // a的从x起始,长度为y的字串,若其后字串长度不满y,则到末尾为止。
a.substr(x); // 从x起始,末尾中止的字串.
printf("%s\n", a.c_str()); // string首元素的地址。
队列queue,优先队列priority_queue
queue函数
push() // 向队尾插入元素
front() || back() // 返回队头/队尾元素
pop() // 弹出队头元素
size() // 长度
empty() // 判断是否为空
q = queue<int>() // 清空queue
priority_queue优先队列(堆)
push() // 插入元素
top() // 返回堆顶元素
pop() // 弹出堆顶元素
优先队列默认为大根堆,如果我们想定义小根堆,有两种方式
(1)heap.push(-x) 插入-x
(2)priority_queue<
栈stack
函数
push() // 栈顶插入元素
top() // 返回栈顶元素
pop() // 弹出栈顶元素
size();
empty();
双端队列deque
双端队列可以看作是加强版的vector,可以从队头和队尾进行插入和删除操作。不过因为效率太低,一般不使用。
size()
empty()
clear()
front() / back()
push_back() / pop_back()
push_front / pop_front()
begin()/end()
[]