priority_queue declaration and bool operator < declaration

有些话、适合烂在心里 提交于 2020-01-07 05:04:08

问题


my problem is:

  • I have my program with 2 class plus the main;

  • I've declared a priority_queue inside a member function of a class;

  • I have to define the comparison and I think the code I should use is:

    // Determine priority (in the priority queue)
    bool operator < (const node & a, const node & b)
    {
      return a.getPriority() > b.getPriority();
    }
    

Question: where Should I insert this piece of code? Could someone help me?

thanks


回答1:


It looks like your operator< is possibly a poor addition to node. Ask yourself: are nodes logically comparable? Is it clear that comparing nodes (outside of the context of priorty_queue) should compare their priority? Maybe it should compare their position, or anything else they might contain. If you supply an operator< it will also make sense to have the other 5 comparison operators. If it's not clear what node < node actually compares, don't provide an operator< for nodes. In cases like this it's better to provide a custom comparer to the priority_queue...

struct NodeComparer
{
    bool operator()(const node& left, const node& right)
    {
        return left.GetPriority() > right.GetPriority();
    }
}

...

std::priority_queue<node, std::vector<node>, NodeComparer> nodeQueue;

This way your priority_queue can work as desired but you don't add illogical functionality to node.




回答2:


This operator should be visible where the priority_queue is declared. As the priority queue exists only in a member I would place the operator's definition right above the given method definition in the .cpp file that implements the method.



来源:https://stackoverflow.com/questions/14981590/priority-queue-declaration-and-bool-operator-declaration

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