STL priority queue and overloading with pointers

前端 未结 2 623
北海茫月
北海茫月 2021-01-05 14:05

This is my first time using a priority queue. I\'m trying to implement Dijkstra\'s algorithm for school and I figured I need a min heap to do this. Right now my nodes are po

相关标签:
2条回答
  • 2021-01-05 15:06

    If I understand your question correctly, I believe what you actually want is to make node_comparison a functor (more specifically, a binary predicate):

    struct node_comparison 
    {
        bool operator () ( const Node* a, const Node* b ) const 
        {
            return a->totalWeight < b->totalWeight;
        }
    };
    

    A functor is a class whose objects provide an overload of the call operator (operator ()) and, therefore, can be invoked with the same syntax you would use for invoking a function:

    Node* p1 = ...;
    Node* p2 = ...;
    node_comparison comp;
    bool res = comp(p1, p2) // <== Invokes your overload of operator ()
    

    Internally, std::priority_queue will instantiate your predicate more or less like I did in the code snippet above, and invoke it that way to perform comparisons between its elements.


    The advantage of functors over regular functions is that they could hold state information (something you probably won't need for the moment, but which often turns out to be desirable):

    #include <cmath>
    
    struct my_comparator
    {
        my_comparator(int x) : _x(x) { }
    
        bool operator () (int n, int m) const
        {
            return abs(n - _x) < abs(m - _x);
        }
    
        int _x;
    };
    

    The above predicate, for instance, compares integers based on how distant they are from another integer provided at construction time. This is how it could be used:

    #include <queue>
    #include <iostream>
    
    void foo(int pivot)
    {
        my_comparator mc(pivot);
        std::priority_queue<int, std::deque<int>, my_comparator> pq(mc);
    
        pq.push(9);
        pq.push(2);
        pq.push(17);
    
        while (!pq.empty())
        {
            std::cout << pq.top();
            pq.pop();
        }
    }
    
    int main()
    {
        foo(7);
    
        std::cout << std::endl;
    
        foo(10);
    }
    
    0 讨论(0)
  • 2021-01-05 15:08

    You would need your comparison functor to implement bool operator()(....), not bool operator<(....):

    struct node_comparison 
    {
       bool operator()( const Node* a, const Node* b ) const 
       {
        return a->totalWeight < b->totalWeight;
       }
    };
    
    0 讨论(0)
提交回复
热议问题