era s'q
era s'q

Reputation: 591

Syntax difference of priority_queue implementing min heap with descending sort of vector

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

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

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 ints 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

Related Questions