优先队列也是队列这种数据结构的一种。它的操作不仅局限于队列的先进先出,可以按逻辑(按最大值或者最小值等出队列)。
底层实现:堆.
这里介绍一下c++里面的优先队列容器—priority_queue
模板声明带有三个参数,priority_queue<Type, Container, Functional>
Type 为数据类型, Container 为保存数据的容器,Functional 为元素比较方式。Container 必须是用数组实现的容器,比如 vector, deque 但不能用 list.STL里面默认用的是 vector. 比较方式默认用 operator< , 所以如果你把后面俩个参数缺省的话,优先队列就是大顶堆,队头元素最大。
基本操作:
#include <bits/stdc++.h>
using namespace std;
int main()
{
srand(time(NULL));
priority_queue<int> pq;
for(int i=0; i<10; i++)
{
int num = rand()%100;
pq.push(num);
}
while(!pq.empty())
{
//queue的队首为front(),注意区分
cout<<pq.top()<<" ";
pq.pop();
}
return 0;
}
你会发现这里优先队列存储的十个随机数每次都是按照从大到小的顺序从队列出队的,这是因为默认情况下优先队列是大顶堆实现.
小顶堆需要自定义:
#include <bits/stdc++.h>
using namespace std;
int main()
{
srand(time(NULL));
priority_queue<int,vector<int>,greater<int> > pq;
for(int i=0; i<10; i++)
{
int num = rand()%100;
pq.push(num);
}
while(!pq.empty())
{
cout<<pq.top()<<" ";
pq.pop();
}
return 0;
}
自定义比较关系:
对于自定义类型,则必须重载 operator< 或者自己写仿函数
#include <bits/stdc++.h>
using namespace std;
bool Mycmp(int a,int b)
{
return a%10<b%10;
}
int main()
{
srand(time(NULL));
priority_queue<int,vector<int>,function<bool(int,int)>> pq(Mycmp);
for(int i=0; i<10; i++)
{
int num = rand()%100;
pq.push(num);
}
while(!pq.empty())
{
cout<<pq.top()<<" ";
pq.pop();
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int x, y;
Node( int a= 0, int b= 0 ):
x(a), y(b) {}
};
bool operator<( Node a, Node b )
{
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x;
}
int main()
{
srand(time(NULL));
priority_queue<Node> pq;
for(int i=0; i<10; i++)
{
int num1 = rand()%10;
int num2 = rand()%10;
pq.push(Node(num1,num2));
}
while(!pq.empty())
{
cout<<pq.top().x<<" "<<pq.top().y<<endl;
pq.pop();
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int x, y;
Node( int a= 0, int b= 0 ):
x(a), y(b) {}
};
struct cmp
{
bool operator() ( Node a, Node b )
{
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x;
}
};
int main()
{
srand(time(NULL));
priority_queue<Node, vector<Node>, cmp> pq;
for(int i=0; i<10; i++)
{
int num1 = rand()%10;
int num2 = rand()%10;
pq.push(Node(num1,num2));
}
while(!pq.empty())
{
cout<<pq.top().x<<" "<<pq.top().y<<endl;
pq.pop();
}
return 0;
}
模拟用堆实现
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class priority_queue
{
private:
vector<int> data;
public:
void push( int t )
{
data.push_back(t);
push_heap( data.begin(), data.end());
}
void pop()
{
pop_heap( data.begin(), data.end() );
data.pop_back();
}
int top()
{
return data.front();
}
int size()
{
return data.size();
}
bool empty()
{
return data.empty();
}
};
int main()
{
priority_queue test;
test.push( 3 );
test.push( 5 );
test.push( 4 );
test.push( 2 );
test.push( 1 );
while( !test.empty() )
{
cout << test.top() << endl;
test.pop();
}
return 0;
}
更多和priority_queue的相关知识后续随着学习深入继续补充完善!