Implement a priority queue in C++. Use libraries iostream, std namespace, C++ language…
- User
Implement a priority queue in C++. Use libraries iostream, std namespace, C++ language classes. An implementation must not use the queue library. Functions for adding, withdrawing (without withdrawal), and withdrawing an element should be described.
- Assistant
Here is an implementation of a priority queue in C++ without using the queue library. It uses the iostream library and the std namespace. The priority queue class contains functions for adding, withdrawing (without withdrawal), and withdrawing an element.
#include <iostream> #include <vector> #include <algorithm> using namespace std; class PriorityQueue { public: void push(int value) { data.push_back(value); push_heap(data.begin(), data.end()); } int top() const { return data.front(); } void pop() { pop_heap(data.begin(), data.end()); data.pop_back(); } bool isEmpty() const { return data.empty(); } private: vector<int> data; }; int main() { PriorityQueue pq; pq.push(3); pq.push(7); pq.push(2); pq.push(5); cout << "Top element: " << pq.top() << endl; // Outputs: 7 pq.pop(); // Withdraws the highest priority element (7) cout << "Top element: " << pq.top() << endl; // Outputs: 5 pq.pop(); // Withdraws the next highest priority element (5) cout << "pq is empty: " << (pq.isEmpty() ? "true" : "false") << endl; // Outputs: false return 0; }