priority_queue的用法和queue基本一样,难点在于自定义类型的自动排序。一共有三种写法。默认是vector作为底层结构。
代码实例1:
class struc{
public:
int x;
int y;
struc(int a, int b): x(a), y(b){}
bool operator<(const struc& b) const //自定义排序。写在类里面必须是const函数!
{
return this->x * this->y > b.x * b.y;
}
};
void priority_queue_test()
{
priority_queue<int> pq1; //默认大顶堆,大的在前面。
priority_queue<int, vector<int>, greater<int> > pq2; //小顶堆,小的在前面
priority_queue<struc> Mypq;
Mypq.push(struc(2, 2));
Mypq.push(struc(1, 5));
while(!Mypq.empty())
{
cout<<Mypq.top().x<<" "<<Mypq.top().y<<endl; //注意priority_queue取头元素是 top();
Mypq.pop();
}
}
代码实例2:
class struc{
public:
int x;
int y;
struc(int a, int b): x(a), y(b){}
};
struct compare{
bool operator()(const struc& a, const struc& b) //自定义排序。
{
return a.x * b.y < b.x * b.y;
}
};
void priority_queue_test()
{
priority_queue<struc, vector<struc>, compare> Mypq; //这种情况就必须写一个struct compare
Mypq.push(struc(2, 2));
Mypq.push(struc(1, 5));
while(!Mypq.empty())
{
cout<<Mypq.top().x<<" "<<Mypq.top().y<<endl; //注意priority_queue取头元素是 top();
Mypq.pop();
}
}