Answers for "priority queue with comparator in cpp"

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

Code answers related to "priority queue with comparator in cpp"

Browse Popular Code Answers by Language