1

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?

1 Answer 1

1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.