Priority Queue Comparison

后端 未结 6 1765
心在旅途
心在旅途 2021-02-05 08:40

I\'m trying to declare a priority queue in c++ using a custom comparison function...

So , I declare the queue as follows:

std::priority_queue

        
相关标签:
6条回答
  • 2021-02-05 08:57
    std::priority_queue<int, std::vector<int>, bool (*)compare(int, int)> pq(compare);
    

    Is another way not mentioned.

    0 讨论(0)
  • 2021-02-05 08:58

    You can use C++11 lambda function. You need to create lambda object, pass it to the template using decltype and also pass it to the constructor. It looks like this:

    auto comp = [] (int &a, int &b) -> bool { return a < b; };
    std::priority_queue<int,std::vector<int>, decltype(comp) > pq (comp);
    
    0 讨论(0)
  • 2021-02-05 09:11

    You can use a typedef. This compiles very well:

    typedef bool (*comp)(int,int);
    bool compare(int a, int b)
    {
       return (a<b);
    }
    int main()
    {
        std::priority_queue<int,std::vector<int>, comp> pq(compare);
        return 0;
    }
    
    0 讨论(0)
  • 2021-02-05 09:12

    This worked perfectly for me.

    struct compare{
        bool operator() (const int& p1,const int& p2 ){
             return p1<p2;
        }
    };
    
    int main(){
        priority_queue<int,vector<int>, compare > qu;
    return 0;
    }
    
    0 讨论(0)
  • 2021-02-05 09:14

    you have to specify function type and instantiate the function in priority_queue constructor.

    #include <functional>
    
    bool compare(int a, int b)
    {
       return (a<b);
    }
    
    std::priority_queue<int, std::vector<int>,
                                  std::function<bool(int, int)>> pq(compare);
    
    0 讨论(0)
  • 2021-02-05 09:24

    The template parameter should be the type of the comparison function. The function is then either default-constructed or you pass a function in the constructor of priority_queue. So try either

    std::priority_queue<int, std::vector<int>, decltype(&compare)> pq(&compare);
    

    or don't use function pointers but instead a functor from the standard library which then can be default-constructed, eliminating the need of passing an instance in the constructor:

    std::priority_queue<int, std::vector<int>, std::less<int> > pq;
    

    http://ideone.com/KDOkJf

    If your comparison function can't be expressed using standard library functors (in case you use custom classes in the priority queue), I recommend writing a custom functor class, or use a lambda.

    0 讨论(0)
提交回复
热议问题