简体   繁体   English

了解使用min stl priority_queue的operator()重载

[英]Understanding operator() overloading with min stl priority_queue

i have been studying on priority_queue. 我一直在研究priority_queue。 when i tried to create a min stl priority_queue, i searched on net and found some tutorial. 当我尝试创建最小stl priority_queue时,我在网上搜索并找到了一些教程。 but i don't understand a few things in the code. 但我不明白代码中的几件事。 so far i have the following code. 到目前为止,我有以下代码。

#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
class compare
{
public:
    bool operator()(const int &a, const int &b)
    {
        return a>b;
    }
};
int main()
{
    priority_queue<int, vector<int>, compare > pq;
    int i,n;
    for(i=1;i<=10;i++)
    {
        pq.push(i);
    }
    while(!pq.empty())
    {
        cout<<pq.top()<<endl;
        pq.pop();
    }
    return 0;
}

questions: 问题:

  1. in the operator function there are two parameters but, when i push element in the queue there is only 1 argument then how this works and compare ? 在运算符函数中有两个参数,但是,当我在队列中推送元素时,只有1个参数,那么它如何工作并进行比较?
  2. what does the declaration of pq mean ? pq的声明是什么意思? i mean why there is <vector<int>> and what does it mean and do ? 我的意思是为什么会有<vector<int>> ,它是什么意思和做什么?

in the operator function there are two parameters but, when i push element in the queue there is only 1 argument then how this works and compare ? 在运算符函数中有两个参数,但是,当我在队列中推送元素时,只有1个参数,那么它如何工作并进行比较?

The comparator is used by the priority queue to compare elements to determine which has the higher priority. 优先级队列使用比较器来比较元素以确定哪个具有更高的优先级。 When you push an element, it compares it with elements already in the queue to determine where to position the new element. 当您推送一个元素时,它将与队列中已有的元素进行比较,以确定将新元素放置在何处。

In this case, the comparator says that the element with the greater value has the greater priority. 在这种情况下,比较器说值越大的元素优先级越高。

what does the declaration of pq mean ? pq的声明是什么意思? i mean why there is <vector<int>> and what does it mean and do ? 我的意思是为什么会有<vector<int>> ,它是什么意思和做什么?

priority_queue is a container adapter . priority_queue是一个容器适配器 It uses a container for storage, and adds extra functionality - in this case, extraction in priority order. 它使用容器进行存储,并添加了额外的功能-在这种情况下,将按优先级提取。 vector<int> specifies that it should use a vector as its storage; vector<int>指定应使用vector作为其存储; that's the default, and you should use that unless you have a good reason not to. 这是默认设置,除非您有充分的理由不这样做,否则应该使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM