Custom Comparator in Priority_queue in C++ STL (original) (raw)

Last Updated : 26 May, 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 Comparator

A 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_queue

The 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 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++

Example

We have **pair of integers inside the priority_queue:

**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

C++ `

#include #include #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, 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;

}

`

Output

The priority queue is : 1 20 1 2 1 1 100 41 100 21 100 11 300 2 300 1

Why do we need a Custom Comparator?

Custom Comparator in priority_queue

In the above code: