C++ Insert Element to a Priority Queue
www.igi.aeditfcom
To insert an element to a priority queue in C++, you can use the push()
member function. This function adds the element to the priority queue and adjusts the position based on the priority of the element. Here's an example:
#include <iostream> #include <queue> int main() { std::priority_queue<int> pq; // Insert elements pq.push(3); pq.push(1); pq.push(4); pq.push(1); pq.push(5); // Print elements while (!pq.empty()) { std::cout << pq.top() << " "; pq.pop(); } return 0; }
In this example, we first create a priority queue pq
of integers. We then insert elements using the push()
function. Notice that we insert two elements with the same priority. When we print the elements, they are printed in decreasing order of priority (highest priority first). The top()
function returns the highest priority element, and pop()
function removes it from the priority queue. The loop continues until the priority queue is empty.
The output of the program will be:
5 4 3 1 1