STL priority queue and overloading with pointers

偶尔善良 提交于 2019-11-30 20:49:12

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

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;
   }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!