STL Priority Queue on custom class

后端 未结 2 1759
难免孤独
难免孤独 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:09

    You need to make your parameter const, because as of now you're giving it a non-cost reference, which means you might modify the object you're comparing with. (Which you aren't, and probably shouldn't).

    You're not being const-correct. Your operator< doesn't make modifications to the Node, so the function should be const:

    bool operator<(const Node &aNode) const;
    

    After that, if you have trouble calling the getTotalCost() function, it's likely that it is not const as well. Mark it as const if it's not already:

    int getTotalCost(void) const;
    

    Your code is now (more) const-correct.

    On a side note, binary operators are usually implemented outside the class:

    class Node
    {
    public:
        // ...
    
        int getTotalCost(void) const;
    
        // ...
    };
    
    bool operator<(const Node& lhs, const Node& rhs)
    {
        return lhs.getTotalCost() < rhs.getTotalCost();
    }
    

提交回复
热议问题