STL Priority Queue on custom class

后端 未结 2 1764
难免孤独
难免孤独 2020-12-08 05:29

I\'m having a lot of trouble getting my priority queue to recognize which parameter it should sort by. I\'ve overloaded the less than operator in my custom class but it does

2条回答
  •  臣服心动
    2020-12-08 06:20

    less::value_type> Means that your comparator compares the pointers to each other, meaning your vector will be sorted by the layout in memory of the nodes.

    You want to do something like this:

    #include 
    struct DereferenceCompareNode : public std::binary_function
    {
        bool operator()(const Node* lhs, const Node* rhs) const
        {
            return lhs->getTotalCost() < rhs->getTotalCost();
        }
    };
    
    // later...
    priority_queue, DereferenceCompareNode> nodesToCheck;
    

    Note that you need to be const-correct in your definition of totalCost.

    EDIT: Now that C++11 is here, you don't need to inherit from std::binary_function anymore (which means you don't need to #include functional)

提交回复
热议问题