C++ : 优先队列(prority_queue)

原始声明

template <class T, class Container = vector<T>,
  class Compare = less<typename Container::value_type> > class priority_queue;

prority_queue默认按降序排列,即队首元素为值最大的。

函数速览

#include   //头文件
prority_queue<type> team;  //创建指定类型的优先队列,可以是模板类型
team.empty()   //若队列为空返回true
team.size()    //返回队列内元素个数(int)
team.top()  	//返回队首元素(优先级最大的) 
team.push(element)		//插入元素,
team.pop()
team.emplace(value)	//构造元素插入队列
team.swap(other_team) //与另一个优先队列交换全部元素以及排序方式

pair的优先队列

以first为第一关键字,second为第二关键字排序

#include 
#include 
#include 
using namespace std;
int main() 
{
    priority_queue<pair<int, int> > a;
    pair<int, int> b(1, 2);
    pair<int, int> c(1, 3);
    pair<int, int> d(2, 5);
    a.push(d);
    a.push(c);
    a.push(b);
    while (!a.empty()) 
    {
        cout << a.top().first << ' ' << a.top().second << endl;
        a.pop();
    }
}

输出:

2 5
1 3
1 2


priority_queue::emplace

Adds a new element to the priority_queue. This new element is
constructed in place passing args as the arguments for its
constructor.

// priority_queue::emplace
#include        // std::cout
#include           // std::priority_queue
#include          // std::string

int main ()
{
  std::priority_queue<std::string> mypq;

  mypq.emplace("orange");
  mypq.emplace("strawberry");
  mypq.emplace("apple");
  mypq.emplace("pear");

  std::cout << "mypq contains:";
  while (!mypq.empty())
  {
     std::cout << ' ' << mypq.top();
     mypq.pop();
  }
  std::cout << '\n';

  return 0;
}

Output:

mypq contains: strawberry pear orange apple

priority_queue::swap

// priority_queue::swap
#include        // std::cout
#include           // std::priority_queue

int main ()
{
  std::priority_queue<int> foo,bar;
  foo.push (15); foo.push(30); foo.push(10);
  bar.push (101); bar.push(202);

  foo.swap(bar);

  std::cout << "size of foo: " << foo.size() << '\n';
  std::cout << "size of bar: " << bar.size() << '\n';

  return 0;
}

Output:

size of foo: 2
size of bar: 3


自定义排序函数

其中bool operator > (Type a,Type b)运算符重载,重载>表示升序排列,队首元素key最小,重载<表示降序排序,队首元素key最大

struct BinaryNode
{
	int w;
	int id;
	int left;
	int right;
};
bool operator > (Node a, Node b)
{
	return a.w > b.w;
}

定义之后,通过以下语句创建一个优先队列F
priority_queue, greater > F;
下面是一个简单示例:

struct st
{
	int num;
};
bool operator > (st a,st b)
{
	return a.num > b.num;
}
int main()
{
	priority_queue<st, vector<st>, greater<st>> q;
	q.push({ 2 });
	q.push({ 1 });
	q.push({ 3 });
	cout << q.top().num << endl;
}

Output:

1


模板类型也可以:


template<typename T>   
struct Node
{
	T data;
	int w;
};
//---------------------------------------------------------------------------
template<typename T>
bool operator > (Node<T> a, Node<T> b)
{
	return a.w > b.w;
}

之后声明语句如下:

priority_queue<Node<char>, vector<Node<char>>, greater<Node<char>> > F; 

你可能感兴趣的:(C/C++,C++,优先队列,STL)