【问题标题】:Compare argument in priority queue比较优先级队列中的参数
【发布时间】:2018-02-13 11:07:55
【问题描述】:

我试图理解 stl 中的优先级队列。我的理解是第三个参数基本上是类型名(在这种情况下是函数指针)。那么,如果它只接受 typename,如果它只接受 typename 而不是实际的函数指针,它将如何访问我的 compare 函数?

#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();
    }

【问题讨论】:

  • 在这种情况下,它不会。查看其constructor,优先级队列采用所选类型的可选比较器。当它类似于std::less&lt;T&gt; 时,默认构造对象就可以了,但是使用函数指针,您必须明确指定要使用的函数,否则您很快就会遇到问题。
  • @Caninonos 那么,我必须像这样发送吗? priority_queue&lt; int,vector&lt;int&gt;,decltype(p) &gt; pq(comp); 但是,当我尝试将参数作为函子发送时,我不需要显式发送函数,为什么?
  • 你也不需要p。只需指定 decltype(comp) * 即可。
  • 是的。好吧,当然,如果你愿意,你也可以给它一个自定义分配器、自定义底层容器等。但这足以构建一个优先级队列,以后不会导致未定义的行为。 (顺便说一句,您是否尝试过以这种方式指定比较函数和不指定比较函数?您应该很快就能看出区别)

标签: c++ stl function-pointers priority-queue decltype


【解决方案1】:

那么,如果它只接受类型名,如果它只接受类型名而不是实际的函数指针,它将如何访问我的比较函数?

有两种选择。

  1. 创建一个可以构造的类,该类具有此功能作为调用运算符。

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

    然后像你写的那样使用,只传递类型名:

    priority_queue< int,vector<int>,comparator > pq;
    
  2. 传递对对象的引用(可能是函数指针)。所以不需要再次构造你的对象:

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

    其中 p 是你之前创建的函数指针。

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

检查priority_queue 类的构造函数。

Constructors of priority_queue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 2020-10-14
    相关资源
    最近更新 更多