目录
1.基础知识
1.vector是变长数组,容器是左闭右开[begin,end)
函数有:size/empty,clear,begin/end,front/back,
push_back()和pop_back()
#include <iostream>
#include <vector>
using namespace std;
int main(){
//vector创建
vector<int> a({
2, 3, 4});
vector<int> b[233];
struct Rec
{
int x, y;
};
vector<Rec> c;
//vector前后查询函数
cout << a[0] << ' ' << *a.begin() << endl;
cout << a.front() << ' ' << a[0] << ' ' << *a.begin() << endl;
//注意back是end的前一位,对应最后的数字
cout << a.back() << ' ' << a[a.size() - 1] << endl;
//三种遍历vector的方法
for(int i = 0; i < a.size(); i++) cout << a[i] << ' ';
cout << endl;
//迭代器遍历法
for(vector<int>::iterator i = a.begin(); i != a.end(); i ++)
cout << *i << ' ';
cout << endl;
for(int x : a) cout << x << ' ';
cout << endl;
//常见函数
cout << a.size() << endl;
cout << a.empty() << endl;
a.clear();
a.push_back(4);
for(auto x : a) cout << x << ' ';
cout << endl;
a.push_back(2);
a.pop_back();
for(auto x: a) cout << x << ' ';
cout << endl;
//迭代器
vector<int>::iterator it = a.begin();
return 0;
}
vector空间不够的时候,通过扩大一倍空间
2.队列:先进先出
循环队列queue
push,pop,front,back
优先队列priority_queue
push,pop,top
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> q;// 队列
//普通队列是循环队列,只能在队头插入,在队尾删除
q.push(1);//在队头插入一个元素
q.pop();//弹出队尾元素
cout << q.front() << endl;//返回队头
cout << q.back() << endl;//返回队尾
queue<double> a;
struct Rec
{
int a, x, y;
//如果不重载小于号,大根堆(优先队列)内无法排序;小根堆重载大于号
bool operator < (const Rec& t) const
{
return a < t.a;
}
};
priority_queue<Rec> d;
d.push({
1, 2});
priority_queue<int> a2;//大根堆
a2.push(1);//插入一个数
a2.top();//取最大值
a2.pop();//删除最大值
//除了队列,优先队列,栈以外stl容器都有clear()函数
//重新初始化一个队列就可以清空一个队列
q = queue<int>();
priority_queue<int, vector<int>, greater<int>> b;//小根堆
priority_queue<pair<int,int>> c;//二元组
return 0;
}
3.栈:先进后出
函数有:
push
pop
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> stk;
stk.push(1);
stk.top();
stk.pop();
return 0;
}
4.双向队列是没有限制的,队列的头和尾都可以
[]随机访问
begin/end
front/back
push_back
push_front
pop_back
pop_front
clear
#include <iostream>
#include <deque>
using namespace std;
int main()
{
deque<int> a;
a.begin(), a.end();
a.front(), a.back();
a.push_back(1), a.push_front(2);
a[0];
a.pop_back(),a.pop_front();
a.clear();
return 0;
}
5.set动态维护一个有序列表
函数:
size/empty/clear
迭代器
begin/end
insert
find
lower_bound/upper_bound
erase
count
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> a; //元素不能重复
multiset<int> b;//元素可以重复
set<int>::iterator it = a.begin();
it ++