Search code examples
c++stlpolymorphismpriority-queue

Why is STL priority queue incorrectly sorrting my class objects


I have overloaded the < operator as shown but every time the program is run my class objects are sorted seemingly randomly.

class Node
{
int decimal_value
public:
    Node(int decimal) : decimal_value(decimal)
    {}
    friend bool operator<(const Node& p1, const Node& p2);
};

 bool operator<(const Node& p1, const Node& p2)
{
    return p1.decimal_value < p2.decimal_value;
}

int main()
{
    Node* n1= new Node(5);
    Node* n2 = new Node(4);

    priority_queue<Node*> my_q;
    my_q.push(n1);
    my_q.push(n2);
}

Is it possibly due to my use of pointers to Nodes rather than Nodes themselves? And if so how can I fix this?


Solution

  • priority_queue<Node*> my_q; will compare elements of type Node* to sort, it will not dereference those pointers for you and call your overloaded operator. And comparison of unrelated pointers has undefined behaviour, but will yield no useful result in your case.

    When you fixed this one, there will be another bug: You never initialize decimal_value, so it's value is undefined/random.

    One solution would be to explicitly specify an comparator:

    struct MyComparator {
        bool operator()(const Node*l, const Node*r) const {
            return l->decimal_value < r->decimal_value;
        }
    };
    
    std::priority_queue<Node*, std::vector<Node*>, MyComparator> q;