To define a custom comparison function for a priority queue of custom objects, you can create a function object (functor) or use a lambda expression that takes two objects of the custom type and returns a boolean value indicating whether the first object should have a higher priority than the second object.
Here's an example of defining a custom comparison function using a lambda expression for a priority queue of Player
 objects:
#include <iostream>
#include <queue>
#include <string>
struct Player {
std::string name;
int score;
};
int main() {
auto cmp = [](const Player& p1,
const Player& p2) {
return p1.score < p2.score;
};
std::priority_queue<Player,
std::vector<Player>, decltype(cmp)> pq(cmp);
pq.push({"Alice", 100});
pq.push({"Bob", 80});
pq.push({"Charlie", 120});
while (!pq.empty()) {
std::cout << pq.top().name << ": "
<< pq.top().score << std::endl;
pq.pop();
}
}
In this example, the lambda expression cmp
compares two Player
objects based on their score
member. The player with a higher score will have a higher priority in the queue.
The custom comparison function is passed as the third template argument to the std::priority_queue
declaration, and an instance of the comparison function is passed to the constructor of the priority queue.
When you run this code, it will output the players in descending order of their scores:
Charlie: 120
Alice: 100
Bob: 80
By defining a custom comparison function, you can easily customize the priority ordering of objects in a priority queue based on your specific requirements.
Answers to questions are automatically generated and may not have been reviewed.
std::priority_queue
Learn how to access objects based on their importance, and how to customise how that priority is determined