1
votes

When I use std::priority_queue as a Min Heap for example, I'd need to do something like this:

struct MyType{
   ...
   int data;
};

auto greaterThanCmp = [](const MyType& a, const MyType& b){ return a > b; };

std::priority_queue<MyType, std::vector<MyType>, greaterThanCmp> minHeap;

My question is: is there an advantage to providing the greaterThanCmp for a Min Heap or would a less than comparer works just as well, had the committee/implementer gone that route.

Or in other words, why did the standard choose one over the other?

I have tried implementing my MinHeap class with a lessThanCmp just for the heck of it. I tested my code, it works fine.

Thank you very much for your response in advance!

1
"why did the standard choose one over the other?" -- because they could not choose both? I suppose you really mean to ask why they specifically chose std::less over std::greater? Also, are you looking at priority_queue in isolation, or would you include the other ordered containers (like std::set) in your question?JaMiT
comparator function simply decides the order of the elements. greaterThan would allow the smallest element to appear first, whereas lessThan allows the largest one to appear first. Standard chose std::less to be default one.aep
I'm guessing there's no particular reason to that. It's probably just that most standard functions use less as the default comparator, and larger values "usually" have more priority.L. F.

1 Answers

1
votes

Once you have a greater object, you can easily make a less object out of it: less ::operator() (a, b) { return greater (b, a) }. So the less requirement is not limiting.