[英]Why do we need to add a vector as an argument in priority queue declaration?
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?
为什么对于max-heap实现,我们不必如此?
Because of template parameters being positional and C++ standard commitee's decision to order the containter type before the comparator type. 由于模板参数的位置和C ++标准提交人决定在比较器类型之前对容器类型进行排序。
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
. -你不能把它指定
b
,而不是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. 对于max-heap,您使用的是
std::less<int>
,它恰好是默认值,因此也可以省略容器类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.