3

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 ?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.