简体   繁体   English

为什么我们需要在优先级队列声明中添加一个向量作为参数?

[英]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.

相关问题 Prim 算法中为什么需要优先级队列 - Why do we need a priority queue in Prim's Algorithm 为什么向量被用作优先队列的第二个参数? - Why is Vector used as a second argument to Priority Queue? 使用更大和向量声明优先级队列 - Declaration of Priority Queue using greater and vector 如何在特定值之后在优先级队列中添加元素? - How do we add an element in a priority queue after a certain value? 为什么需要单位向量(换句话说,为什么需要归一化向量)? - Why do we need a Unit Vector (in other words, why do we need to normalize vectors)? 比较优先级队列中的参数 - Compare argument in priority queue OpenCV,findContours-为什么我们需要一个 <vector<vector<Point> &gt;存储轮廓? 为什么不只是 <vector<Point> &gt;? - OpenCV, findContours - Why do we need a <vector<vector<Point>> to store the contours? Why not just <vector<Point>>? 为什么我需要传递一个比较器来构造一个priority_queue,当它是一个lambda时,而不是当它是std :: greater时? - Why do I need pass a comparator to construct a priority_queue when it is a lambda, but not when it is std::greater? 为什么我们需要使用std :: vector :: pointer来访问元素? - Why do we need to use std::vector::pointer to access elements? 为什么我们需要对unique_ptr的vector进行移动构造? - Why do we need a move constructor for vector of unique_ptr?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM