Open In App

Custom Comparator in Priority_queue in C++ STL

Last Updated : 26 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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,

  • data_type: Type of the priority queue.
  • container: Container is passed as an underlying container to store the elements.
  • comparator: Comparator decides the ordering of elements.

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,

  • When true is returned, it means the order is NOT correct and swapping of elements takes place.
  • When false is returned, it means the order is correct and NO swapping of elements takes place.

Different ways to implement custom comparator, refer this article - Comparator in C++

Example

We have pair of integers inside the priority_queue:

  • First element of the pair is sorted based on Ascending order. (Smaller first)
  • Second element of the pair is sorted based on Descending order. (Larger first)

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 <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;
}

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?

  • In Complex objects or pairs of data, we may need a different set of orders that are not entirely Ascending or Descending.
  • Comparator in the case of priority_queue decides the ordering of elements, which is basically in the competition among the elements, it decides who needs to be at the top of the priority queue.
  • In the case of Min-Heap, the greater<int> was used.

Custom Comparator in priority_queue

In the above code:

  • Time Complexity: O(Log K), where K is the size of the heap. If Total insertions are N, then it is O(N*LogK). In the above case, the K = N, therefore it boils down to O(N*LogN).
  • Space Complexity: O(K), where K is the size of the heap.

Next Article

Similar Reads