Implement a queue in which each element has its own priority in C++ (an element and its…
- User
Implement a queue in which each element has its own priority in C++ (an element and its corresponding priority are entered into the queue). 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 a simple priority queue implementation in C++ using a priority vector:
#include <iostream> #include <vector> #include <algorithm> class PriorityQueue { public: void push(int element, int priority) { queue.push_back(std::make_pair(element, priority)); std::sort(queue.begin(), queue.end(), compare); } int top() { if (queue.empty()) { throw std::out_of_range("Accessing empty queue"); } return queue.back().first; } void pop() { if (queue.empty()) { throw std::out_of_range("Popping from empty queue"); } queue.pop_back(); } int queueSize() { return queue.size(); } private: std::vector<std::pair<int, int>> queue; static bool compare(const std::pair<int, int> &a, const std::pair<int, int> &b) { return a.second < b.second; } }; int main() { PriorityQueue pq; pq.push(3, 10); pq.push(5, 15); pq.push(1, 5); pq.push(7, 25); pq.push(2, 2); while(pq.queueSize() > 0) { std::cout << "Top element: " << pq.top() << std::endl; pq.pop(); } return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.