Reputation: 591
The syntax to implement min-heap using priority_queue STL is
std::priority_queue<int, std::vector<int>, std::greater<int> > my_min_heap;
whereas, the syntax of implementing a sort()
for vector in descending order is
sort(a.begin(), a.end(), greater<int>());
My question is sort uses () after greater but priority_queue does not. Why is that?
Upvotes: 1
Views: 73
Reputation: 122133
Here
std::priority_queue<int, std::vector<int>, std::greater<int> > my_min_heap;
std::greater<int>
is a template parameter, note that it is inside <>
. It is a type. On the other hand, here
sort(a.begin(), a.end(), greater<int>());
an instance of that type is created and passed to sort
. Also sort
has a template parameter for the comparator, but it is deduced from the argument (to be of type std::greater<int>
), so there is no need to specify it explicitly.
More specifically std::greater<int>
is a functor ie a type that has an overload for the function call operator. To create an instance and use that to compare two int
s you could write:
bool x = std::greater<int>()(5,3);
/* the type */
// ^ call constructor
// ^ call the objects operator()
However, typically the same function object is reused for many comparisons, as is the case with std::sort
.
Upvotes: 1