Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to add a vector as an argument in priority queue declaration?

Tags:

c++

stl

Whenever I want to create a min-heap using a priority queue (which creates a max-heap by default), I need to pass a comparator and also a vector of the required type to be sorted, something like this:

std::priority_queue<int, std::vector<int>, std::greater<int> > pq;

Why do we do this? And why do we not have to the same for a max-heap implementation?

like image 325
Karan Singh Avatar asked Mar 05 '23 15:03

Karan Singh


1 Answers

Because of template parameters being positional and C++ standard commitee's decision to order the containter type before the comparator type.

Just like with a function like this:

void foo(int a = 1, int b = 2);

- you can't call it specifying b, but not a.

For max-heap, you're using std::less<int>, which happens to be the default, therefore you can omit the container type as well.

like image 175
LogicStuff Avatar answered Apr 27 '23 01:04

LogicStuff