Custom Comparison Function for Priority Queue

How can I define a custom comparison function for a priority queue of custom objects?

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.

Priority Queues using std::priority_queue

Learn how to access objects based on their importance, and how to customise how that priority is determined

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Removing a Specific Element from Priority Queue
Is it possible to remove a specific element from a priority queue without popping the top element?
Priority Queue with Unique Elements
How can I ensure that a priority queue contains only unique elements?
Priority Queue with Dynamic Priorities
Can I update the priority of an element already in the priority queue?
Priority Queue with Stable Ordering
How can I ensure stable ordering in a priority queue when elements have the same priority?
Priority Queue with Custom Container
Can I use a custom container as the underlying container for a priority queue?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant