How do I use heterogeneous lookup with std::priority_queue?

In C++, heterogeneous lookup with `std::priority_queue` can be accomplished by utilizing a custom comparator. By defining a custom struct or function object that overrides the comparison operator, one can control how the elements are prioritized in the queue. Below is an example of how to implement this with a user-defined class.

#include #include #include // Define a custom structure struct Item { int value; std::string name; Item(int v, std::string n) : value(v), name(n) {} }; // Custom comparator for the priority queue struct CompareItem { bool operator()(const Item &a, const Item &b) { return a.value < b.value; // Higher value has higher priority } }; int main() { // Create a priority queue with custom comparator std::priority_queue, CompareItem> pq; // Add items to the priority queue pq.push(Item(10, "Item A")); pq.push(Item(5, "Item B")); pq.push(Item(20, "Item C")); // Display items based on priority while (!pq.empty()) { Item item = pq.top(); std::cout << item.name << " with value " << item.value << std::endl; pq.pop(); } return 0; }

C++ priority_queue heterogeneous lookup custom comparator example