优先队列底层是用堆来实现的。在优先队列中,队首元素一般是队列中优先级最高的那个
但是,可以在任意时候往优先队列里添加元素,而优先队列会自动调整结构,使每次队首元素都是优先级最大的
要想使用优先队列,只需要#include < queue > 和using namespace std就可以了
但是,优先队列的元素智能通过top()函数来访问,而没有front()和back()函数
例子:
#include相关实用函数 push()#include using namespace std; int main() { priority_queue q; q.push(3); q.push(1); q.push(2); cout << q.top() << endl; return 0; //输出3 }
作用:将元素x入队,时间复杂度为O(logN),N为当前队列的元素个数
top()作用:访问队首元素,时间复杂度O(1)
pop()作用:令队首元素出队,时间复杂度同push()
empty()作用:判断优先队列是否为空,为空返回true,不为空返回false,时间复杂度O(1)
size()作用:返回优先队列内元素的个数,时间复杂度为O(1)
#include优先队列内元素优先级设置 基本数据类型的优先级设置#include using namespace std; int main() { priority_queue q; q.push(3); q.push(1); q.push(2); q.pop(); cout << q.top() << endl; cout << q.size() << endl; cout << q.empty() << endl; return 0; //输出2,2,0 }
首先,第一行与第二行的定义优先队列是等价的。
其中less< int >表示数字大的优先级大,greater< int >表示数字小的优先级大,优先级越高,越先被输出,如果是其他基本数据类型例如,char,double等,则更换int就可
//基本数据类型优先级设置 priority_queue, less > q; priority_queue q; priority_queue , greater > q;
#include对结构体类型的优先级设置#include using namespace std; int main() { //基本数据类型优先级设置 priority_queue , greater > q; q.push(3); q.push(5); q.push(0); cout << q.top() << endl; return 0; //输出0 }
对结构体的优先级设置则需要使用重载运算符了,直接上代码会好一点
//结构体类型优先级设置 #include#include #include using namespace std; struct Fruit { string name; int price; }; //这里的重载运算符与sort()函数的cmp类似,但是效果相反 struct cmp { bool operator ()(Fruit f1,Fruit f2) { //效果与greater<>一致,即价格小的优先级高,若是小于号,价格大的优先级高 return f1.price > f2.price; } }; int main() { priority_queue , cmp> q; Fruit f1, f2, f3; f1.name = "橙子"; f1.price = 10; f2.name = "苹果"; f2.price = 15; f3.name = "香蕉"; f3.price = 8; q.push(f1); q.push(f2); q.push(f3); cout << q.top().name << " " << q.top().price << endl; return 0; }
输出
同理,其他的STL容器也可以通过同样的方式来定义优先级
注:
使用top()函数前,必须用empty()判断优先队列是否为空,否则可能因为对空而出现错误
若结构体内数据较为庞大(例如出现了字符串或数组),可使用引用来提高效率,此时比较类的参数中需要加上"const"和"&"
bool operator ()(const Fruit &f1,const Fruit &f2) {
//效果与greater<>一致,即价格小的优先级高
return f1.price > f2.price;
}



