如何将3个元素放在c++的Priority_queue中
我一直在研究Leetcode中的C ++中的Priority_queue,我从解决方案中找到了此代码 我知道这是最小堆,但不明白这将如何存储3个元素给Minheap。
- IS
vector< int>
获取matrix [r] [0]
,vector< vector< vector< int>>>>
get> r r r 和更大<>
获取0
???? - 为什么我们需要放置
Priority_queue< int,vector< int> Minheap
avector< int
要使最小堆?
I been studying priority_queue in c++ from Leetcode and I found this code from solution
I understand that this is minimum heap but don't understand how is this storing 3 elements to minHeap.
- is
vector<int>
getsmatrix[r][0]
,vector<vector<int>>
getsr
andgreater<>
gets0
???? - Why do we need to put
priority_queue<int,vector<int>,greater<int>> minHeap
avector<int>
to make Minimum heap?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,让我们看一下
minheap
类中的模板参数的含义。来自 cppreference :
因此,对于
minheap
,它包含vector&lt; int&gt;
对象。它使用vector&lt; vector&lt; int&gt;&gt;
作为基础存储,以包含这些vector&lt; int&gt;
对象。 &lt;&gt; 比较两个vector&lt; int
对象来决定它们的顺序。它使用
更大的 >表示?
比较
参数用于确定哪个元素在顶部。默认情况下,Priority_queue
使用LIST&lt;&gt;
,这意味着较大的元素在顶部。通过使用更大的&lt;&gt;
,它会翻转比较的方向,因此较小的元素在顶部。这就是使它成为“最小”堆的原因。现在,查看 push :
push
仅接受一个参数,该参数是类型value_type
的参数,在这种情况下为vector&lt; int&gt;
。因此,该行
实际上是将单个
向量&lt;
添加到minheap
中。该vector&lt; int&gt;
中包含的值是矩阵[r] [0]
,r
和0
。First, let's look at the meaning of the template arguments in the class of
minHeap
.From cppreference:
So, for
minHeap
, it containsvector<int>
objects. It uses avector<vector<int>>
as the underlying storage to contain thesevector<int>
objects. And it usesgreater<>
to compare twovector<int>
objects to decide what order they go in.What does the
greater<>
signify? TheCompare
argument is used to decide which element goes on top. By default,priority_queue
usesless<>
, which means that larger elements go on top. By usinggreater<>
instead, it flips the direction of the comparison, so smaller elements go on top. This is what makes it a "min" heap.Now, looking at the call to push:
push
is only accepting a single argument, and the argument is of typevalue_type
, which in this case isvector<int>
.So the line
Is actually adding a single
vector<int>
tominHeap
. The values contained in thatvector<int>
arematrix[r][0]
,r
, and0
.