Answers for "write own comparator for priority queue"

C++
8

how to use comparator funtion in priority queue in c++

// suppose you want to apply comparator on pair <int, string>
// declaration of priority queue
priority_queue<pair<int, string>, vector<pair<int, string>>, myComp> pq;
// here myComp is comparator
struct myComp {
  bool operator()(
    pair<int, string>& a,
    pair<int, string>& b)
  {
    return a.first > b.first;
    // can write more code if required. depends upon requirement.
  }
};
// another way 
 auto compare = [](int lhs, int rhs){
  return lhs < rhs;
};

priority_queue<int, vector<int>, decltype(compare) > pq(compare);
Posted by: Guest on November-30-2021
3

priority queue java comparator

// Java program to demonstrate working of 
// comparator based priority queue constructor
import java.util.*;
  
public class Example {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        // Creating Priority queue constructor having 
        // initial capacity=5 and a StudentComparator instance 
        // as its parameters
        PriorityQueue<Student> pq = new 
             PriorityQueue<Student>(5, new StudentComparator());
                  
             
        } 
    }
} 
  
class StudentComparator implements Comparator<Student>{
              
            // Overriding compare()method of Comparator 
                        // for descending order of cgpa
            public int compare(Student s1, Student s2) {
                if (s1.cgpa < s2.cgpa)
                    return 1;
                else if (s1.cgpa > s2.cgpa)
                    return -1;
                                return 0;
                }
        }
  
Posted by: Guest on January-07-2022

Code answers related to "write own comparator for priority queue"

Browse Popular Code Answers by Language