queue
queue就是队列,
在STL中主要实现了一个先进先出的容器
使用queue应该先添加头文件#include<queue>
queue<typename>name;
queue常用函数
- push(),将x入队,时间复杂度为O(1) front(),back(),分别可以获得队首元素和队尾元素,时间复杂度为O(1)
- front(),back(),分别可以获得队首元素和队尾元素,时间复杂度为O(1)
- pop(),pop()令队首元素出队,时间复杂度为O(1)
- empty(),empty()检查queue是否为空,返回true则空,返回false则非空,时间复杂度为O(1)
- size(),size()返回queue内元素的个数,时间复杂度为O(1)
当需要实现广度优先搜索时可以不用自己动手实现一个队列而是用queue作为代替以实现程序的准确性,另外使用front()和pop()函数前必须先用empty()判断队列是否为空,否则可能因为队空而发生错误
priority_queue
priority_queue是优先队列
头文件还是#include<queue>
定义:priority_queue<Type, Container, Functional>
Type 就是数据类型。(int ,double等.)
Container 就是容器类型(Container必须是用数组实现的容器,默认vector,但不能用 list。)
Functional 就是比较的方式(可以自定义,默认从小到大排序)
关于自定义排序方式下面会有说明
//一般声明有
priority_queue <int> p1;
priority_queue<int,vector<int> , less<int> >q;//与上面等价,降序排序
priority_queue<int,vector<int> , greater<int> >q;//升序排序
pari的比较,先比较第一个元素,第一个相等比较第二个
priority_queue<pair<int,int> >p;
自定义数据类型的比较
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int x;
Node() {}
Node(int x):x(x) {} //赋值
bool operator<(const Node& a) const//从大到小
{
return x<a.x;
}
};
int main()
{
priority_queue<Node> p;
for(int i=1; i<=5; i++)//输入数据
p.push(Node(i));
while(!p.empty())
{
cout<<p.top().x<<' ';
p.pop();
}
return 0;
}

————————————————————————————————————————————————————————————————————————————————————————
下面是自定义类型queue的进一步应用
虽然有限队列有默认的排列顺序,但在很多情况下默认排序并不满足我们的需求,这就需要我们们自定义排列顺序
可以在结构体内部重载运算符,改变符号的功能
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int x;
Node() {}
Node(int x):x(x) {} //赋值
bool operator<(const Node& a) const //从大到小
{
return x<a.x;
}
bool operator>(const Node& a) const//从小到大
{
return x>a.x;
}
};
int main()
{
priority_queue<Node> p1;//默认从大到小 等价于priority_queue<Node,vector<Node>,less<Node> > p1;
for(int i=1; i<=5; i++)
p1.push(Node(i));
cout<<"p1 = ";
while(!p1.empty())
{
cout<<p1.top().x<<' ';
p1.pop();
}
cout<<endl;
priority_queue<Node,vector<Node>,greater<Node> > p2;//从小到大
for(int i=5; i>=1; i--)
p2.push(Node(i));
cout<<"p2 = ";
while(!p2.empty())
{
cout<<p2.top().x<<' ';
p2.pop();
}
return 0;
}

可以在结构体内部重载运算符,改变符号号的功能
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int x;
Node() {}
Node(int x):x(x) {} //赋值
};
struct cmp
{
/*bool operator() (const Node& a,const Node& b) //从大到小
{
return a.x<b.x;
}*/
bool operator() (const Node& a,const Node& b) //从小到大
{
return a.x>b.x;
}
};
int main()
{
priority_queue<Node,vector<Node>,cmp > p;
for(int i=1; i<=5; i++)
p.push(Node(i));
cout<<"p = ";
while(!p.empty())
{
cout<<p.top().x<<' ';
p.pop();
}
cout<<endl;
return 0;
}

STL队列与优先队列详解
本文详细介绍了STL中的队列(queue)和优先队列(priority_queue)的使用方法,包括基本操作如push、pop及front等,并探讨了如何自定义数据类型及其排序方式以满足不同场景的需求。
1404

被折叠的 条评论
为什么被折叠?



