#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pi;
struct Compare
{
bool operator()(pi const & a, pi const & b)
{
if(a.second < b.second)
{
return true;
}
else if(a.second > b.second)
{
return false;
}
else
{
if(a.first > b.first)
{
return true;
}
return false;
}
}
};
int main()
{
priority_queue<pi , vector, Compare>q;
q.push({1, 5});
q.push({5, 15});
q.push({7, 15});
q.push({10, 2});
q.push({1, 10});
cout<<q.top().first<<" "<<q.top().second<<endl;
return 0;
}
Need an explanation on the output...how the compare function is working?
It takes any two index i and j from the queue and then compare them -:
First by their second value , and whose second value is smaller , let that pair index be as i , then in queue index i th pair will come before jth pair.
Secondly , if second value of both pair is same then comparison between first value of both pair will take place and as like above the pair with lower first value comes before the other pair.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
#include <iostream>
#include <queue>
#include<vector>
using namespace std;
class Car {
public:
int x;
int y;
int id;
Car(int id,int x,int y)
{
this->id=id;
this->x=x;
this->y=y;
}
int dist()
{
return x*x+y*y;
}
void print(){
cout<<"ID"<<id<<" ";
cout<<"Location"<<x<<","<<y<<endl;
}
};
class CarCompare{ //using functor
public:
bool operator()(Car a,Car b)
{
return a.dist()<b.dist();
}
};
int main()
{
CarCompare cc;
priority_queue<Car,vector<Car>,CarCompare> Q; //use with functor
//shouldn't the above line be priority_queue<Car,vector<Car>,CarCompare()> Q;
//as we need to call the object
int x[10]={5,6,17,18,9,11,0,3};
int y[10]={1,-2,8,9,10,91,1,2};
for (int i = 0; i < 8; ++i) {
Car c(i,x[i],y[i]);
Q.push(c);
// insert an object in priority_queue by using
// the Person class constructor
}
while (!Q.empty()) {
Car c1 = Q.top();
c1.print();
Q.pop();
}
return 0;
}