Customize C++ Priority Queue
In C++, you can use the std::priority_queue class to implement a priority queue. By default, std::priority_queue uses std::less for comparison, meaning that the priority of elements is determined by the greatest element being placed at the front of the queue. If you want to customize the sorting rule of the priority queue, you can achieve this by using a custom comparison function or a custom class.
Utilize a custom comparison function:
#include <iostream>
#include <queue>
struct CustomCompare {
bool operator()(int a, int b) {
// 自定义排序规则,按照元素的绝对值大小进行排序
return std::abs(a) > std::abs(b);
}
};
int main() {
std::priority_queue<int, std::vector<int>, CustomCompare> pq;
pq.push(3);
pq.push(-5);
pq.push(2);
pq.push(-1);
while (!pq.empty()) {
std::cout << pq.top() << " ";
pq.pop();
}
return 0;
}
Output result:
-5 3 -1 2
Utilizing custom classes:
#include <iostream>
#include <queue>
class MyClass {
public:
int value;
MyClass(int v) : value(v) {}
};
struct CustomCompare {
bool operator()(const MyClass& a, const MyClass& b) {
// 自定义排序规则,按照元素的value进行排序
return a.value > b.value;
}
};
int main() {
std::priority_queue<MyClass, std::vector<MyClass>, CustomCompare> pq;
pq.push(MyClass(3));
pq.push(MyClass(-5));
pq.push(MyClass(2));
pq.push(MyClass(-1));
while (!pq.empty()) {
std::cout << pq.top().value << " ";
pq.pop();
}
return 0;
}
The output result:
-5 -1 2 3
By defining your own comparison function or class, you can implement custom sorting rules for a priority queue.