Priority Queues using std::priority_queue

Custom Comparison Function for Priority Queue

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

Illustration representing computer hardware

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved