优先队列:优先队列是一个容器,允许对数时间插入的代价,常熟市建的最大值(或者最小值)。
使用STL的std::priority_queue
需要包含头文件queue
定义如下:
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class priority_queue;
container默认是vector,compare是比较函数,默认是less,当然可以自己定义比较函数。
常用的函数:
empty() //如果优先队列为空,则返回真
pop() //删除第一个元素
push() //插入一个元素
size() //返回优先队列中拥有的元素的个数
top() //返回优先队列中有最高优先级的元素
测试例子:
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
void print(priority_queue<int> q){
while (!q.empty()){
cout << q.top() << " ";
q.pop();
}
cout << endl;
}
int main(){
priority_queue<int> q;
for (int n:{1,2,3,4,5,6,7})
q.push(n);
cout << q.top() << endl;
cout << "Is q empty?" << q.empty() <<endl;
print(q);
cout << "插入:0" << endl;
q.push(0);
print(q);
cout << "删除:" << endl;
q.pop();
print(q);
return 0;
}
ubuntu@VM-188-113-ubuntu:~/test_cpp$ ./priority_queue_test2
7
Is q empty?0
7 6 5 4 3 2 1
插入:0
7 6 5 4 3 2 1 0
删除:
6 5 4 3 2 1 0
自己定义比较函数:
/*
*本程序测试std::priority_queue的基本用法
* */
#include <iostream>
#include <functional>
#include <queue>
#include <vector>
using namespace std;
struct Node{
int f;
bool operator<(const Node& node) const{
return f < node.f;
}
};
class cmp{
public:
bool operator()(const Node& n1, const Node& n2) const{
return n1 < n2;
}
};
int main(){
priority_queue<Node, vector<Node>, cmp> q;
Node n1; n1.f = 5;
Node n2; n2.f = 4;
Node n3; n3.f = 3;
Node n4; n4.f = 2;
Node n5; n5.f = 1;
q.push(n1);q.push(n2);q.push(n3);q.push(n4);q.push(n5);
while (!q.empty()){
cout << q.top().f << endl;
q.pop();
}
return 0;
}
ubuntu@VM-188-113-ubuntu:~/test_cpp$ ./priority_queue_test
1 2 3 4 5