【暑假集训笔记】STL之priority_queue优先队列的常用三种方法

/**
常用三种方式:
	1.默认输出最大值的声明:
		priority_queue<int> pq;//最大值优先队列
	2.含参数输出最小值的声明:
		几个参数只要注意下数据类型即可,<vector> 等参数不用包含头文件
		priority_queue<int,vector<int>,greater<int> > pq;//最小值优先队列
		
	3.自定义优先级(重载运算符):
		#include<functional>
		struct node{
			friend bool operator< (node n1, node n2)
			{
				return n1.priority < n2.priority;
			}
			int priority;
			int value;
		};
		value为值,priority为优先级。
		通过自定义operator<操作符来比较元素中的优先级。
		
		
		但是:
		struct node
		{
			friend bool operator> (node n1, node n2)
			{
				return n1.priority > n2.priority;
			}
			int priority;
			int value;
		};
		G++编译失败 标准库默认使用<操作符来确定它们之间的优先级关系
队列操作:
	empty() 如果队列为空返回真

	pop() 删除对顶元素

	push() 加入一个元素

	size() 返回优先队列中拥有的元素个数

	top() 返回优先队列对顶元素
*/
#include<iostream>
#include<functional>
#include<queue>
using namespace std;
typedef struct node{
    friend bool operator< (node n1, node n2)
    {
        return n1.p < n2.p;
    }
    int p;
    int val;
}Node;
int main()
{
    int a[] = {1,2,3,4,5};

    priority_queue<int> q1;
    for(int i = 0; i < 5; i++)
        q1.push(a[i]);
    for(int i = 0; i < 5; i++){
        cout<<q1.top()<<" ";
        q1.pop();
    }

    priority_queue<int, vector<int>, greater<int> >q2;
    for(int i = 0; i < 5; i++)
        q2.push(a[i]);
    for( int i = 0; i < 5; i++)
    {
        cout<<q2.top()<<" ";
        q2.pop();
    }

    priority_queue<Node> q;
    Node b[2];
    b[0].p = 1; b[0].val = 2; 
    b[1].p = 4; b[1].val = 3; 
	q.push(b[0]);
	q.push(b[1]);
	cout<<q.top().p<<' '<<q.top().val<<endl;
	q.pop();
	cout<<q.top().p<<' '<<q.top().val<<endl;
	q.pop();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/F_zmmfs/article/details/81383044
今日推荐