how do we know a.dist() > b.dist () is giving nearer car…i am confused about working of > and < signs …
Priority queue 2
Lets talk in case of integers rather than this specific case. Lets say our comparator is:
void operator()(int a,int b){
return (a<b);
}
Always perceive the return value of the comparator as answer to the question:
Can ‘a’ come before ‘b’ ?
So, in the comparator above, if we ask this question, it will return “true” iff (a<b). This means that if (a<b), ‘a’ can come before ‘b’ . So, if you were using this comparator for ‘sort’ function (in STL), in the final (sorted) array, ‘a’ will appear before ‘b’ if (a<b).(You can extend this logic for each pair of numbers and conclude that array will be sorted in ascending order).
Similarly if you were to use this comparator for priority_queue (in STL), format the question to:
Can ‘a’ come below ‘b’ ?
So, in the case of above comparator, ‘a’ can come below ‘b’ iff (a<b), which means, if a<b, then ‘a’ will go below (in priority_queue) and ‘b’ will go on top. So the top element will always be greater than those below it (aka max_heap).
So, back to your doubt,
return a.dist()>b.dist();
is giving nearest car because if a.dist()>b.dist(), Car ‘a’ can go below Car ‘b’, thus the Car on the top will have lesser distance than the Car(s) below it (aka min_heap).
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.