Last Updated : 23 Jul, 2025
In C++, a priority queue is an STL container that utilizes the Heap Data Structure. It is useful when we need to retrieve the min or max element in constant time O(1), while insertion and deletion operations are performed in O(log n) time.
Custom ComparatorA custom comparator is a function or function-like object (functor) used with algorithms or data structures, such as sorting or priority_queue. It modifies their default behavior.
Syntax of Custom Comparator in Priority_queueThe following is the syntax for using a priority queue with a custom comparator:
C++
priority_queue<data_type, container, comparator> ds;
where,
Similarly to passing the greater<datatype> inbuilt comparator, we can also pass a user-defined comparator to priority_queue by declaring a Compare class and overloading the operator() function.
C++
class Compare {
public:
bool operator()(data_type a, data_type b) {
if(cond) {
return true;
}
return false;
}
};
In the above code,
Different ways to implement custom comparator, refer this article - Comparator in C++
ExampleWe have pair of integers inside the priority_queue:
C++Input:
{100,11} {100,41} {100,21} {300,1} {300,2} {1,1} {1,2} {1,20}
Output:
Top to Bottom:
1 20
1 2
1 1
100 41
100 21
100 11
300 2
300 1
#include <iostream>
#include <queue>
#define PII pair<int, int>
using namespace std;
// Based on first part in ascending and
// second part in descending first basis
class Compare {
public:
bool operator()(PII a, PII b)
{
if (a.first > b.first) {
return true;
}
else if (a.first == b.first
&& a.second < b.second) {
return true;
}
return false;
}
};
int main() {
priority_queue<PII, vector<PII>, Compare> ds;
ds.push({ 100, 11 });
ds.push({ 100, 41 });
ds.push({ 100, 21 });
ds.push({ 300, 1 });
ds.push({ 300, 2 });
ds.push({ 1, 1 });
ds.push({ 1, 2 });
ds.push({ 1, 20 });
cout << "The priority queue is : \n";
while (!ds.empty()) {
cout << ds.top().first << " "
<< ds.top().second << "\n";
// heapify happens
ds.pop();
}
return 0;
}
The priority queue is : 1 20 1 2 1 1 100 41 100 21 100 11 300 2 300 1Why do we need a Custom Comparator?
In the above code:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4