admin管理员组

文章数量:1623793

priority_queue

(个人学习记录用,有问题感谢指正 orz)

priority_queue<type, container, cmp >
// type为数据类型,container为容器类型(默认vector),cmp为排序方式(默认降序)

0.创建优先队列

priority_queue<int>pq;
== priority_queue<int,vector<int> >pq;   
== priority_queue<int,vector<int>,less<int> >pq;
priority_queue<int,vector<int>,greater<int> >pq;
priority_queue<int,vector<int>,cmp >pq;
priority_queue<node,vector<node>,cmp >pq;
priotity_queue<node >pq;
== priority_queue<node,vector<node> >pq;

1.基本操作

top() 访问队头元素
pop() 弹出队头元素
empty() 空返回0,否则返回1
size() 返回队列内元素个数
push(1)    push({1,2})  插入元素到队尾 (并排序)
swap(pq1,pq2) 交换两个队列

2.遍历优先队列

while(!pq.empty()){
	cout<<pq.top()<<endl;
	//cout<<pq.top().x<<" "<<pq.top().y<<endl;
	pq.pop();
}

3.自定义优先级

法一、重写仿函数:
(1) 一元

struct cmp{
  bool operator()(int x, int y)
  {
     return x>y;
  }
};

(2) 多元

struct node
{
    int x,y;
};
struct cmp
{
    bool operator()(node &a,node &b)
    {
    	if(a.x==b.x)return a.y<b.y;
        return a.x<b.x;
        //此处为x相等时,y大的优先级高,否则是x大的优先级高,根据所需写
    }
};

法二、运算符重载:
(1)一元

struct node{
	int x;
	bool operator<(const node a)const
	{
		return x<a.x;
	}
};

(2)多元

struct node{
	int x,y;
	bool operator<(const node a)const
	{
		if(x==a.x)return y>a.y;
		return x>a.x; 
	}
}

4.测试代码

#include<bits/stdc++.h>
#include<queue>
using namespace std;

//struct node{
//	int x,y;
//};

//struct cmp{
//	bool operator()(int x,int y){
//		return x>y;
//	}
//};

//struct cmp{
//	bool operator()(node &a,node &b){
//		if(a.x==b.x)return a.y<b.y;
//		return a.x<b.x;
//	}
//};

struct node{
	int x,y;
	bool operator < (const node a)const
	{
		if(x==a.x)return y>a.y;
		return x>a.x;
	}
};

int main(){
//	priority_queue<int,vector<int>,cmp >pq;
	priority_queue<node,vector<node> >pq;
//	pq.push({1});
//	pq.push({4});
//	pq.push({9});
//	pq.push({3});
	pq.push({1,2});
	pq.push({1,3});
	pq.push({9,1});
	pq.push({3,6});
	while(!pq.empty()){
		cout<<pq.top().x<<" "<<pq.top().y<<endl;
		pq.pop();
	}
//	while(!pq.empty()){
//		cout<<pq.top().x<<endl;
//		pq.pop();
//	}
}

本文标签: 队列priorityqueue