Sure, here's an implementation of a priority queue in C++ without using any external libraries:
#include <iostream>
#include <vector>
#include <algorithm>
template <typename T>
class PriorityQueue {
public:
PriorityQueue() : size_(0) {}
void push(const T& item, const T& priority) {
items_.push_back({item, priority});
while (size_ > 0 && items_[size_ - 1].priority < items_[0].priority) {
items_[size_ - 1] = items_[0];
size_--;
}
items_.push_back(items_[size_ - 1]);
}
T& peak() {
return items_[0].item;
}
T& pop() {
if (size_ == 0) {
throw std::runtime_error("Population queue is empty.");
}
T& item = items_[0].item;
items_.erase(items_.begin());
while (size_ > 0 && items_[size_ - 1].priority < items_[0].priority) {
size_--;
}
return item;
}
int size() const {
return size_;
}
private:
std::vector<std::pair<T, T>> items_;
int size_;
};
int main() {
PriorityQueue<int> pq;
pq.push(1, 10);
pq.push(3, 20);
pq.push(5, 30);
std::cout << "Peak: " << pq.peak() << std::endl;
std::cout << "Popped: " << pq.pop() << std::endl;
std::cout << "Size: " << pq.size() << std::endl;
return 0;
}
This implementation uses a std::vector to store the items and their corresponding priorities. It keeps the items in a sorted order based on their prior