C++ Priority Queue Methods

In C++, the STL priority_queue class template provides a priority queue, which is a container that allows fast retrieval of the maximum or minimum element. The priority_queue uses a heap as an underlying container, and the elements are stored in such a way that the first element is always the largest or smallest.

Some of the most commonly used methods of the priority_queue class are:

  • push(): Inserts an element into the priority queue.
  • pop(): Removes the first element from the priority queue.
  • top(): Returns a reference to the first element in the priority queue.
  • size(): Returns the number of elements in the priority queue.
  • empty(): Returns true if the priority queue is empty; otherwise, returns false.

Additionally, the priority_queue class supports a constructor that takes a comparison function as an argument. This function determines the order in which the elements are stored in the priority queue. By default, the priority_queue uses the less-than operator (<) for comparison, which results in a max-heap. To create a min-heap, you can pass a greater-than comparison function to the constructor.