C++STL之priority_queue优先队列容器

特征:就是队列中最大元素总是在队首

*优先队列使用方法

#include<iostream>
#include<queue>
using namespace std;

int main()
{
	priority_queue<int> pq;
	pq.push(2);
	pq.push(0);
	pq.push(1);
	pq.push(5);
	cout<<pq.size()<<endl;
	
	while(pq.empty() != true)
	{
		cout<<pq.top()<<" ";
		pq.pop();
	}
	cout<<endl;
	
	return 0;
}

*重载"<"操作符来定义优先级

如果优先队列的元素类型是结构体,可以通过在结构体中重载"<"操作符的方法来修改优先队列的优先性。

#include<iostream>
#include<string>
#include<queue>
using namespace std;

struct Info
{
	string name;
	float score;
	
	bool operator < (const Info& a)const
	{
		//由小到大排序 
		return a.score < score;
	} 
};

int main()
{
	priority_queue<Info> pq;
	Info info;
	info.name = "CaiCai";
	info.score = 68.5;
	pq.push(info);
	
	info.name = "Zhejiang";
	info.score = 90;
	pq.push(info);
	
	info.name = "Ningbo";
	info.score = 78.2;
	pq.push(info);
	
	while(pq.empty() != true)
	{
		cout<<pq.top().name<<" : "<<pq.top().score<<endl;
		pq.pop();
	}
	return 0;
}

*重载“()”操作符来定义优先级

如果优先队列元素不是结构体类型,可以通过重载"()"操作符的方式来定义优先级,当然若元素是结构体类型,也可以通过重载"()"操作符的方式来定义优先级,而不是一定要在结构体内重载"<"操作符。

#include<iostream>
#include<vector>
#include<queue>
using namespace std;

struct cmp
{
	bool operator () (const int& a, const int& b)
	{
		//由小到大 
		return a < b;
	}
};

int main()
{
	priority_queue<int, vector<int>, cmp> pq;
	pq.push(2);
	pq.push(0);
	pq.push(1);
	pq.push(5);
	pq.push(10);
	pq.push(23);
	while(pq.empty() != true)
	{
		cout<<pq.top()<<" ";
		pq.pop();
	}
	cout<<endl; 
	
	return 0;
} 

你可能感兴趣的:(C++STL之priority_queue优先队列容器)