Open In App

Custom Comparator in Priority_queue in C++ STL

Prerequisites:

Priority_queue<template datatype> is a very famous STL Container generally used when we need to use Heap Data structure.



 The Characteristics of the heap data structure are:

Syntax:



priority_queue<data_type, container, comparator> ds;

Parameters:

Why do we need a Custom Comparator?

Custom Comparator in priority_queue

class Compare {
    public:
       bool operator()(T a, T b){
           if(cond){
               return true;
           }
           return false;
      }
};

Example:

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

Code of the above example:




// C++ Program to implement
// Custom Comparator in Priority Queue
#include <iostream>
#include <queue>
#define PII pair<int, int>
 
// Pair of Ints = PII
using namespace std;
 
// based on first part in ascending and second part in
// descending first basis
class Compare {
public:
    bool operator()(PII below, PII above)
    {
        if (below.first > above.first) {
            return true;
        }
        else if (below.first == above.first
                 && below.second < above.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";
        ds.pop(); // heapify happens
    }
 
    return 0;
}

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

Time and Space Complexity:

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.


Article Tags :