C++ priority_queue

蝸牛一步一步往上爬發表於2016-09-07
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