C++ priority_queue

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

优先队列默认采用vector实现,是最大堆。

Priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering criterion.

This context is similar to a heap, where elements can be inserted at any moment, and only the max heap element can be retrieved (the one at the top in the priority queue).

Priority queues are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are popped from the “back” of the specific container, which is known as the top of the priority queue.


Member function


- empty : Test whether container is empty (public member function )
size Return size (public member function )
- top : Access top element (public member function )
- push : Insert element (public member function )
- emplace : Construct and insert element (public member function )
- pop : Remove top element (public member function )
- swap : Swap contents (public member function )

  vector<int> nums{ 1, 9, 5, 7, 4 };
  priority_queue<int> pq(nums.begin(), nums.end());// 9,7,5,4,1

  cout << "top : " << pq.top() << endl;
  pq.pop();// 7,5,4,1
  cout << "after pop(), top : " << pq.top() << endl;
  pq.push( 6 );// 7,6,5,4,1
  pq.pop();// 6,5,4,1
  cout << "after pop(), top : " << pq.top() << endl;

输出:

top : 9
after pop(), top : 7
after pop(), top : 6

最小堆

  vector<int> nums{ 1, 9, 7, 4 };
  priority_queue<int, vector<int>, greater<int>> pq(nums.begin(), nums.end());
  //1, 4, 7, 9

  cout << "top : " << pq.top() << endl;
  pq.pop(); // 4, 7, 9
  cout << "after pop(), top : " << pq.top() << endl;
  pq.push( 5 ); // 4, 5, 7, 9
  pq.pop(); // 5, 7, 9
  cout << "after pop(), top : " << pq.top() << endl;

输出:

top : 1
after pop(), top : 4
after pop(), top : 5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值