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 ?
1 Answer
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.
6 Comments
Viraj
So you mean greater would be a logical default comparator ?
1201ProgramAlarm
No. Everywhere else the STL needs a comparison it defaults to less.
Viraj
Okay, irrespective of the default to less, logically shouldn't it be greater ?
1201ProgramAlarm
@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.Aditya
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. |