优先级队列priority_queue

今天在移植代码的时候看见一个priority_queue 的定义,开始当成了普通队列来看待,后面发现不对啊,为什么有3个参数,搞不懂了,于是查了一下,知道这个是优先级队列,啊哈,又学到新的东西了,这几天移植代码,一直没有学习到新知识,今天就花点时间学习一下。刚好我自己有个程序优化可以用到。

priority_queue是(优先队列)就是一个封装好的堆结构。

1.定义

priority_queue<Type, Container, Functional>

Type为数据类型, Container为保存数据的容器,Functional为元素比较方式。

如果不写后两个参数,那么容器默认用的是vector,比较方式默认用operator<,也就是优先队列是大顶堆,队头元素最大。

这个地方当然可以自己定义封装operator<操作。

class cmd

{
    bool operator()(const int a,const int b)
    {
        return a>=b;
    }
}

priority_queue<int,vector<int>,cmd> m_que;

2.插入元素push()

for(int i = 0;i<10;i++)
{
    m_que.push(i);
}

3.取出元素top(),删除元素pop()

while(!m_que.empty())
{
    int i = m_que.top();
    m_que.pop();
}

4.获取元素大小size()

m_que.size();

实例

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

struct  node
{
	int a;
	int b;
	int c;
};

struct cmd
{
	bool operator()(const node a, const node b)
	{
		if (a.a > b.a)
			return true;
		else if (a.a == b.a)
		{
			if (a.b > b.b)
			{
				return true;//往后排
			}
			else
			{
				return false;
			}
		}
		else
			return false;
	}
};
int main()
{
	priority_queue<node,vector<node>,cmd> m_que;

	struct node n1 = { 2, 2, 3 }, n2 = { 1, 3, 4 }, n3 = { 2, 1, 5 };
	m_que.push(n1);
	m_que.push(n2);
	m_que.push(n3);

	while (!m_que.empty())
	{
		cout << m_que.top().a << "------" << m_que.top().b << endl;
		m_que.pop();
	}
	return 0;
}

输出:

1----3

2----1

2-----2

猜你喜欢

转载自blog.csdn.net/liyu123__/article/details/82426341