queue
队列是一种先进先出的数据结构
初始化和其他容器类似
#include<queue>
queue<int>q;
方法函数
//1.front() 返回队首元素
//2.back() 返回队尾元素
//3.push() 在队尾添加一个元素
//4.pop() 删除第一个元素
//5.size() 得到队列元素个数
//6.empty() 判空
#include<iostream>
#include<queue>
using namespace std;
int main()
{
queue<int>q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
int num = q.size();
for (int i = 0; i < num; i++)
{
cout << q.front() << endl;
q.pop();
}
if (q.empty())
cout << "true";
else cout << "false";
return 0;
}
模拟实现队列
使用数组的方式来模拟实现队列的函数功能
int main()
{
return 0;
}
双端队列
首尾都能进行插入和删除的队列
#include<deque>
deque<int>dq;//初始化
方法函数
//1.push_back(x)/push_front(x) 把a插入在后端或者前端
//2.back()/front() 访问后端/前端的元素
//3.pop_back()/pop_front() 删除后端/前端的元素
//4.erase(iterator it) 删除队列中的一个元素
//5.erase(first,end) 删除first到end的元素,都是地址,前闭后开
//6.empty() 判断deque是否为空
//7.size() 返回元素个数
//8.clear() 清空deque
deque可以排序
//从小到大排序
deque<int>dq;
sort(dq.begin(),dq.end());
//从大到小排序
sort(dq.begin(),dq.end(),greater<int>);
priority_queue优先队列
优先队列就是一个堆,大堆或者是小堆都可以
用处为:在每一次进行增删查改的时候,都会自动的底层进行排序
//头文件
#include<queue>
//初始化定义
priority_queue<int>pq;
函数方法
//1.top() 访问队首元素
//2.push() 入队
//3.pop() 出队(堆顶元素)
//4.size() 队列元素个数
//5.empty() 判断是否为空
//注意:优先队列没有clear方法,只能通过top()访问堆顶元素
大堆小堆
大小之分是根据初始化的参数决定的,less<..>表示数字大的优先级大,堆顶为最大的数字,greater<..>表示堆顶为最小的数字
1.priority_queue<int>pq;//初始化这样等同于加上less
2.priority_queue<int,vector<int>,less<int>>pq;//1和2相同建立大堆
3.priority_queue<int,vector<int>,greater<int>>pq;//建立小堆
less和greater实际上是编译器写好的比较大小的方式,我们也可以自定义来实现
#define _CRT_SECURE_NO_WARNINGS
#include<queue>
#include<iostream>
using namespace std;
struct cmp1
{//定义比较结构体,
bool operator()(int x, int y)
{
return x < y;//小的优先级高 ,从小到大排
}
};
int main()
{
priority_queue<int,vector<int>, cmp1>pq;
pq.push(1);
pq.push(2);
pq.push(3);
pq.push(4);
pq.push(5);
int num = pq.size();
for (int i = 0; i < num; i++)
{
cout << pq.top() << endl;
pq.pop();
}
return 0;
}
如果是类类型的话,需要重载比较的方法,在node类中自定义比较函数,就不需要定义cmp比较结构体
#define _CRT_SECURE_NO_WARNINGS
#include<queue>
#include<iostream>
using namespace std;
struct node
{
int x,y;
node(int x, int y)
{
this->x = x;
this->y = y;
}
bool operator < (const node& a) const
{//直接传入一个参数,不必要写friend
return x > a.x;//优先级大的为x小的值,升序排列
}
//或者是
friend bool operator<(node a,node b)
return a.x>b.x;//根据x的数值大小进行升序排序
};
int main()
{
priority_queue<node>pq;
pq.push(node(1, 2));
pq.push(node(2, 2));
pq.push(node(3, 2));
pq.push(node(4, 2));
pq.push(node(5, 2));
int num = pq.size();
for (int i = 0; i < num; i++)
{
cout << pq.top().x << endl;
pq.pop();
}
return 0;
}
对于pair双元组,排序的规则是默认的,默认先对pair的first进行降序排序,然后对于second进行降序排序
//对于first先排序,大的排在前面,如果first元素相同,再对second元素排序,保持大的在前面
//
int main()
{
priority_queue<pair<int,int>>pq;
pq.push({1,2});
pq.push({1,1});
pq.push({3,2});
while(!pq.empty())
{
cout<<pq.top().first<<" "<<pq.top().second<<endl;
pq.pop();
//输出结果为3 2
//1 2
//1 1
}
// cout<<pq.top().second<<" "<<pq.top().first<<endl;
//输出结果为2 3
//2 1
//1 1
return 0;
}
pair<int,int>二元组的排序规则是默认的,先first再second