C++,优先级队列,项目未排序

发布于 2024-10-04 13:43:52 字数 1031 浏览 6 评论 0原文

我的优先级队列有问题:

std::priority_queue <NodePrio, std::vector<NodePrio>, sortNodesByPrio> PQ;

位置

struct NodePrio
{
Node *node;
double priority;

NodePrio() : node(NULL), priority(0) {}
NodePrio(Node *node_, double priority_) : node(node_), priority(priority_) {}
};

class sortNodesByPrio
{
public:
    bool operator () (const NodePrio &n1, const NodePrio  &n2)   const;
}


bool sortNodesByPrio::operator () (const NodePrio &n1, const NodePrio &n2) const
{
return n1.priority < n2.priority;
}

重复推送新元素的

PQ.push(NodePrio(node, distance));

之后,并且从任何时间点它们都没有排序(见下文)...我尝试调试代码,比较器代码已被重复执行...

Step1: 
push (node, 55.33);

PQ:
[0] 55.33

Step2:
push (node, 105.91);

PQ:
[0] 105.91
[1] 55.33

Step 3:
push (node, 45.18);

PQ:
[0] 105.91
[1] 55.33
[2] 45.18

Step 4:
push (node, 70.44);

PQ:
[0] 105.91
[1] 70.44
[2] 45.18
[3] 55.33   //Bad sort

I have a problem with the priority queue:

std::priority_queue <NodePrio, std::vector<NodePrio>, sortNodesByPrio> PQ;

where

struct NodePrio
{
Node *node;
double priority;

NodePrio() : node(NULL), priority(0) {}
NodePrio(Node *node_, double priority_) : node(node_), priority(priority_) {}
};

and

class sortNodesByPrio
{
public:
    bool operator () (const NodePrio &n1, const NodePrio  &n2)   const;
}


bool sortNodesByPrio::operator () (const NodePrio &n1, const NodePrio &n2) const
{
return n1.priority < n2.priority;
}

After repeatedly pushing new elements

PQ.push(NodePrio(node, distance));

and from any point in time they are not sorted (see bellow)... I tried to debug the code, the comparator code has been repeatedly performed...

Step1: 
push (node, 55.33);

PQ:
[0] 55.33

Step2:
push (node, 105.91);

PQ:
[0] 105.91
[1] 55.33

Step 3:
push (node, 45.18);

PQ:
[0] 105.91
[1] 55.33
[2] 45.18

Step 4:
push (node, 70.44);

PQ:
[0] 105.91
[1] 70.44
[2] 45.18
[3] 55.33   //Bad sort

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

执手闯天涯 2024-10-11 13:43:52

根据您显示的“示例结果”,您似乎不了解优先级队列是什么。

优先级队列保证当您从其中删除元素(使用 top()pop())时,元素将按优先级顺序删除。元素不按优先级顺序存储,而是存储在堆中。

您可以查阅您最喜欢的算法书籍或网站,以获取有关优先级队列如何存储其元素的更多信息。

Based on the "sample results" you show, it looks like you don't understand what a priority queue is.

A priority queue guarantees that when you remove elements from it (using top() and pop()), the elements will be removed in priority order. The elements are not stored in priority order, they are stored in a heap.

You can consult your favorite algorithms book or website for more information on how a priority queue stores its elements.

街道布景 2024-10-11 13:43:52

尝试更改

return n1.priority() < n2.priority();

return n1.priority < n2.priority;

Try changing

return n1.priority() < n2.priority();

to

return n1.priority < n2.priority;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文