I am confused as to why the priority_queue in C++ uses less as a default comparator and implement a max heap ? Doesn't less arrange the elements in ascending order ?
Asked
Active
Viewed 1,045 times
1 Answers
1
For consistency. less
is used as the default comparator for many algorithms and containers, and us mere humans don't have to try and remember which one uses which comparator by default since they are all the same.

1201ProgramAlarm
- 32,384
- 7
- 42
- 56
-
So you mean greater would be a logical default comparator ? – Viraj Oct 04 '15 at 04:12
-
No. Everywhere else the STL needs a comparison it defaults to less. – 1201ProgramAlarm Oct 04 '15 at 04:14
-
Okay, irrespective of the default to less, logically shouldn't it be greater ? – Viraj Oct 04 '15 at 04:51
-
@Viraj If you want a min heap, yes. If you want a max heap, no. `priority_queue` is just a queue and doesn't know what you want to do with it. – 1201ProgramAlarm Oct 04 '15 at 04:55
-
Sorry but I don't understand what you mean. To rephrase my question, if less used as a comparator to sort a vector, sorts it in ascending order, why is it used in a priority queue to return a max element first (max heap). – Viraj Oct 04 '15 at 05:07
-
If consistency of using `less` was the reason, they could have made the default implementation of `priority_queue` to behave like `min heap` using `less` instead of the non-intuitive `max heap` using `less`. My point is there must be some other reason/constraint. – Aditya Shaw Apr 10 '23 at 07:21