简体   繁体   English

比较优先级队列中的参数

[英]Compare argument in priority queue

I am trying to understand the priority queue in stl. 我试图了解stl中的优先级队列。 What I have understood is that the third argument is basically typename(in this case function pointer). 我了解的是,第三个参数基本上是typename(在这种情况下为函数指针)。 So,if it just accepts the typename, how will it have access over my compare function when it will implement its operations if it just accept typename and not actual function pointer? 那么,如果它只接受类型名,如果只接受类型名而不是实际的函数指针,它将在实现其操作时如何访问我的比较函数?

#include <iostream>
    #include <bits/stdc++.h>
    using namespace std;
    bool comp(int a,int b){
        return a<b;
    }

    int main()
    {
        int (*p)(int,int);
        p=comp;
        priority_queue< int,vector<int>,decltype(&comp) > pq;
        decltype(p) a;
        cout<<typeid(a).name();
    }

So,if it just accepts the typename, how will it have access over my compare function when it will implement its operations if it just accept typename and not actual function pointer? 那么,如果它只接受类型名,如果只接受类型名而不是实际的函数指针,它将在实现其操作时如何访问我的比较函数?

There are two options for you. 有两个选项供您选择。

  1. Make a class, that can be constructed which has this function as a call operator. 创建一个可以构造为具有此函数作为调用运算符的类的类。

     struct comparator { bool operator()(int a, int b) { return comp(a, b); } }; 

    Then use like you written, pass only the typename: 然后像您写的那样使用,仅传递类型名称:

     priority_queue< int,vector<int>,comparator > pq; 
  2. Pass a reference to your object (which may be a function pointer). 将引用传递给您的对象(可能是函数指针)。 So no need for constructing your object again: 因此,无需再次构造对象:

     priority_queue< int,vector<int>,decltype(p) > pq(p) 

    Where p is the function pointer you made before. 其中p是您之前创建的函数指针。

     bool (*p)(int,int); p=comp; priority_queue< int,vector<int>,decltype(p) > pq(p); 

Check the constructors of the priority_queue class. 检查priority_queue类的构造函数。

Constructors of priority_queue priority_queue构造方法

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

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